-3

我正在尝试将以下代码片段从 PHP 转换为 C# 或 VB.NET 这是来自用于从外部 webhook 捕获 JSON 字符串的 PHP 页面。

// Get the POST body from the Webhook and log it to a file for backup purposes...
$request_body = file_get_contents('php://input');
$myFile = "testfile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $request_body);
fclose($fh);

// Get the values we're looking for from the webhook
$arr = json_decode($request_body);
foreach ($arr as $key => $value) {
    if ($key == 'properties') {
        foreach ($value as $k => $v) {
            foreach ($v as $label => $realval) {
                if ($label == 'value' && $k == 'zip') {
                    $Zip = $realval;                    
                }
                elseif($label == 'value' && $k == 'firstname') {
                    $Fname = $realval;
                }
                elseif($label == 'value' && $k == 'lastname') {
                    $Lname = $realval;
                }
                elseif($label == 'value' && $k == 'email') {
                    $Email = $realval;
                }
                elseif($label == 'value' && $k == 'phone') {
                    $Phone = $realval;
                    $Phone = str_replace("(", "", $Phone);
                    $Phone = str_replace(")", "", $Phone);
                    $Phone = str_replace("-", "", $Phone);
                    $Phone = str_replace(" ", "", $Phone);
                }
                //need the other values as well!
            }
        }
    }
}

ETA:我现在从流中得到了 json 字符串。仍在试图弄清楚如何解析这个。JSON 字符串格式是我无法控制的,但我基本上需要获取“属性”节点。

4

4 回答 4

2

这个答案将为您指明如何将流写入文件的正确方向。您的情况下的流是Request.InputStream,相当于php://input.

要处理 JSON 部分,请查看@YYY 的答案。

于 2012-10-26T20:19:42.650 回答
1

如果我理解正确,这基本上就是您要尝试做的事情。但正如其他人提到的那样。JSON.NET 是更好的选择。

private void Request()
{
    //Makes Request
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/Test.php");
    request.ContentType = "application/json; charset=utf-8";
    request.Accept = "application/json, text/javascript, */*";
    request.Method = "POST";
    using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
    {
        writer.Write("{id : 'test'}");
    }

    //Gets response
    WebResponse response = request.GetResponse();
    Stream stream = response.GetResponseStream();
    string json = "";
    using (StreamReader reader = new StreamReader(stream))
    {
        //Save it to text file
        using (TextWriter savetofile = new StreamWriter("C:/text.txt"))
        {
            while (!reader.EndOfStream)
            {
                string line = reader.ReadLine();
                savetofile.WriteLine(line);
                json += line;
            }
        }
    }

    //Decodes the JSON
    DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(MyCustomDict));
    MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
    MyCustomDict dict = (MyCustomDict)dcjs.ReadObject(ms);

    //Do something with values.
    foreach(var key in dict.dict.Keys)
    {
        Console.WriteLine( key);
        foreach(var value in dict.dict[key])
        {
            Console.WriteLine("\t" + value);
        }
    }

}
[Serializable]
public class MyCustomDict : ISerializable
{
    public Dictionary<string, object[]> dict;
    public MyCustomDict()
    {
        dict = new Dictionary<string, object[]>();
    }
    protected MyCustomDict(SerializationInfo info, StreamingContext context)
    {
        dict = new Dictionary<string, object[]>();
        foreach (var entry in info)
        {
            object[] array = entry.Value as object[];
            dict.Add(entry.Name, array);
        }
    }
    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        foreach (string key in dict.Keys)
        {
            info.AddValue(key, dict[key]);
        }
    }
}

归功于这个人

于 2012-10-26T20:20:31.960 回答
1

.NET 的基础库没有任何真正好的方法来处理 JSON 输入。相反,请查看Json.NET,它是一个高性能的 3rd 方库,可满足此需求。

链接页面上有使用示例。

于 2012-10-26T19:45:42.273 回答
0

既然你们这些无情的暴徒欺负我,我觉得至少有义务记录下我的进步。

   Using inputStream As New StreamReader(Request.InputStream)
        JSON = inputStream.ReadToEnd
        If JSON.Length > 0 Then
            Using writer As StreamWriter = New StreamWriter("c:\temp\out.txt")
                writer.Write(JSON)
            End Using
        End If
    End Using
于 2012-10-26T20:27:34.173 回答