我试图通过 JSON 和 Json.NET 在 C# .NET 应用程序和一些 PHP 服务器端之间进行一些通信。我正在发布 Json 字符串,但我无法访问(或未正确发送)服务器端的字符串。我的 $_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}