我的目的是将JSON从C#发送到PHP,然后在PHP端进一步解码,以便将其用于我的目的。
PHP结束时的错误是:
警告:json_decode()期望参数1为字符串,数组在第24行的/home3/alsonsrnd/public_html/test/sync.php中给出
我使用以下代码使用C#发送JSON到我的PHP代码:
private void sendData()
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://alnnovative.com/test/sync.php");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"user\":\"test\"," +
"\"password\":\"bla\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
在PHP上我使用条带斜线和json_decode()来解码JSON。我的PHP代码给出的错误是接收到的字符串是一个数组而不是JSON,因此它不能使用json_decode对其进行解码。可能是什么原因呢?因为我从C#发送正确格式的JSON
我的PHP代码是:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$json=$_POST;
if (get_magic_quotes_gpc()){
$json = stripslashes($json);
}
//Decode JSON into an Array
$data = json_decode($json);
}
答案 0 :(得分:0)
首先,您必须更改Content-Type标题
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
其次,您要以错误的格式发送数据
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "json=" + "{\"user\":\"test\"," +
"\"password\":\"bla\"}"; ;
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
最后,你以错误的方式接收数据,$ _POST是一个数组,所以
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['json']))
{
$json=$_POST['json'];
if (get_magic_quotes_gpc()){
$json = stripslashes($json);
}
//Decode JSON into an Array
$data = json_decode($json, true);
}