-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.InputStreamphp://inputです。

JSON部分を処理するには、@YYYの回答を参照してください。

于 2012-10-26T20:19:42.650 に答える
1

.NETのベースライブラリには、JSON入力を処理するための本当に良い方法がありません。代わりに、このニーズに対応する高性能のサードパーティライブラリであるJson.NETをご覧ください。

リンク先のページに使用例があります。

于 2012-10-26T19:45:42.273 に答える
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 に答える
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 に答える