【问题标题】:JSON sent from C# but not received as JSON in php从 C# 发送的 JSON 但未在 php 中作为 JSON 接收
【发布时间】:2016-01-29 09:34:50
【问题描述】:

我的目的是将 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);
}

【问题讨论】:

标签: c# php json


【解决方案1】:

首先,您必须更改 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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 2017-12-18
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多