Json.NET and PHP communication
本文关键字:communication PHP and NET Json | 更新日期: 2023-09-27 18:32:14
我正在尝试通过 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}
你必须使用 application/json 而不是 application/x-www-form-urlencoded。
也许这会有所帮助!