将代码片段从PHP转换为C#或VB.NET

时间:2012-10-26 19:28:16

标签: c# php vb.net json

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

// 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 个答案:

答案 0 :(得分:2)

This answer会指出如何将流写入文件的正确方向。您案例中的流为Request.InputStream,相当于php://input

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

答案 1 :(得分:1)

.NET的基础库没有任何处理JSON输入的好方法。相反,请查看Json.NET,这是一个高性能的第三方库,满足这种需求。

链接页面上有一些用法示例。

答案 2 :(得分: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]);
        }
    }
}

归功于this guy

答案 3 :(得分: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