1

Json.NET を使用した JSON を介して、C# .NET アプリと一部の PHP サーバー側の間で何らかの通信が行われるようにしようとしています。Json 文字列を POST していますが、サーバー側の文字列にアクセスできません (または正しく送信されていません)。$_POST 変数が空のように見え、Json 文字列にアクセスするために使用するキーがわかりません。誰でも何か提案できますか?

私のC#コード:

TestClass ts = new TestClass("Some Data", 3, 4.5);
string json = JsonConvert.SerializeObject(ts);

HttpWebRequest request =
    (HttpWebRequest)WebRequest.Create("http://localhost/testJson.php");
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = json.Length;

StreamWriter sw = new StreamWriter(request.GetRequestStream());
sw.Write(json);   
sw.Close();

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string responseJson = sr.ReadToEnd();
sr.Close();

TestClass returnedTS =
    JsonConvert.DeserializeObject<TestClass>(responseJson);

私のPHPコード:

<?php
    require("TestClass.php");
    $json = json_decode($_POST);
    $ts = new TestClass();
    $ts->someString = $json['someString'];
    $ts->someDouble = $json['someDouble'];
    $ts->someInt = $json['someInt'];
    $return_json = json_encode($ts);
    echo $return_json;
?>

私の出力:

<b>Warning</b>:  json_decode() expects parameter 1 to be string, array given in
<b>C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\testJson.p
hp</b> on line <b>4</b><br />
{"someString":null,"someInt":null,"someDouble":null}
4

1 に答える 1

3

application/x-www-form-urlencoded の代わりに application/json を使用する必要があります。

たぶんそれが役立ちます!

于 2012-08-27T07:12:52.010 に答える