2012-10-26 56 views
-3

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

// 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字符串格式不在我的控制范围内,但我基本上需要获取“属性”节点。

+0

只是谷歌“打开并阅读文件的C#”... – devHead

+1

你有多远?发布一些C#/ VB.NET代码,你试过 – Bogdan

+0

还没有得到很多,因为无法弄清楚我通过file_get_contents('php:// input'')的方式。我试图使用System.Net.WebClient – WhiskerBiscuit

回答

2

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

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

+0

你可能想看看这个[元问题]中的#6(http://meta.stackexchange.com/a/118694/148672) –

+0

@ConradFrix谢谢你指向我,因为那里的指导原则是很有帮助。但我不确定这里的情况是否如此。我所链接的答案仅仅意味着为OP提供了一个起点,它仅仅为这里提出的问题提供了部分解决方案。如果我误解了某些内容,请告诉我。 – Bogdan

1

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

链接页面上有用法示例。

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

+0

我有点卡在自定义词典。您的代码部分反序列化,但JSON的“内部”属性似乎丢失 – WhiskerBiscuit

+0

JSON来自外部站点,并且它似乎在阵列中有数组。不知道如何在这里发布它,因为它是一个烂摊子 – WhiskerBiscuit

+0

很不幸,我没有正确的设置没有你的直接代码看到这个JSON。但我认为这将是修改MyCustomDict以在foreach循环中查找嵌入数组的问题。 – Corylulu

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