【问题标题】:JSON string selected from database ends up in wrong format when encoding JSON in PHP在 PHP 中编码 JSON 时,从数据库中选择的 JSON 字符串格式错误
【发布时间】:2018-02-16 03:19:53
【问题描述】:

我有一个数据库,其中有几个简单的文本列和一个列,其中包含一个带有附加数据的 JSON 字符串。

我有一个 PHP 脚本,它在这个数据库中选择数据,并将结果编码为 JSON,然后将其发送回我的 C# 应用程序,在那里我将 JSON 字符串反序列化为自定义对象。

一切都很好,直到我最近将 JSON 字符串列添加到数据库中,而我的 C# 反序列化器 (Newtonsoft) 未能将该列反序列化为应转换为的 C# 对象。

以下是 JSON 结果返回 C# 的方式(反序列化之前):

{
 "Status":"OK",
 "Result":
   [
    {
      "Name":"This is a name",
      "Address":"This is an address",
      "CustomData":"[{\"CustomDataName\":\"Name\",\"CustomDataLabel\":\"Data Label\",\"CustomDataValue\":\"Some random value\",\"CustomDataType\":\"Text\",\"Permission\":\"1\"},{\"CustomDataName\":\"Something random\",\"CustomDataLabel\":\"\",\"CustomDataValue\":\"Value goes here\",\"CustomDataType\":\"Text\",\"Permission\":\"1\"}]  
    }
   ],
 "GeneralErrorMessage":""
}

此 JSON 的 CustomData 属性应转换为 C# 中的 CustomDataClass 对象,该对象具有 CustomDataName、CustomDataLabel、CustomDataType、CustomDataValue、Permission 属性。

但是,您可以看到字符串中有反斜杠,这表明我没有从数据库中正确选择它,或者我没有以正确的方式编码/解码。

C#部分:

//reading the response from the PHP script...
using (StreamReader reader = new StreamReader(stream))
{
    while (!reader.EndOfStream)
    {
        jsonresponse += reader.ReadLine();
    }
}

//converting the string response from the PHP script to our object
JSONResponseClass jrt = JsonConvert.DeserializeObject<JSONResponseClass>(jsonresponse);
//fails on this line ^

JSONResponseClass 如下所示:

public class JSONResponseClass 
{
    public String Status;

    public List<myObject> Result;

    public String GeneralErrorMessage;
}

myObject 类如下所示:

public class myObject
{
    public String Name;

    public String Address;

    public List<CustomDataClass> CustomData;
}

尝试反序列化时 C# 中的错误消息:

错误转换值 "[{"CustomDataName":"asdasdasdas","CustomDataLabel":"asdasdasdas","CustomDataValue":"RandomValue...","CustomDataType":"Text","Permission":"1 "},...]" 输入 'System.Collections.Generic.List`1[NameSpace.myObject]'。路径 'Result[0].CustomData',第 1 行,位置 2167。

PHP部分(数据库选择和JSON编码:

$returnedSelection = SelectValuesFromDatabase(); //get the values from the database

$obj = new stdClass();
$obj->Status = "OK";
$obj->Result = $returnedSelection;
$obj->GeneralErrorMessage = "";
die(json_encode($obj));

function SelectValuesFromDatabase()
{
    $con = SetupConnector();
    $ResultArray = array(); //return values will be stored in this array

    $sql = "SELECT name as Name, address as Address, jsondata as CustomData FROM data_table";

    if($result=mysqli_query($con, $sql))
    {
        while($row = mysqli_fetch_array($result))
        {
            $ResultArray[] = $row;
        }   
    }
    return $ResultArray;
}

为了在来自 PHP 的 JSON 中获取正确的 CustomData 值,需要执行哪些必要步骤?

【问题讨论】:

  • JSON 字符串的来源是什么(在某些地方带有转义引号),谁生成了它,然后又是谁在使用它?
  • 同一个应用程序正在将其插入数据库中。

标签: php mysql json mysqli


【解决方案1】:

正如您在图像中看到的,您的 json 无效,您对“CustomData”进行了编码,然后在最终对象中进行了第二次编码。如果您删除第一个编码操作,一切都会好起来的。

您的 CustomData 字段已经是一个 json。所以你应该先解码。 您需要使用以下内容更改您的 php 代码。

$returnedSelection = SelectValuesFromDatabase(); //get the values from the database

$obj = new stdClass();
$obj->Status = "OK";
$obj->Result = $returnedSelection;
$obj->GeneralErrorMessage = "";
die(json_encode($obj));

function SelectValuesFromDatabase()
{
    $con = SetupConnector();
    $ResultArray = array(); //return values will be stored in this array

    $sql = "SELECT name as Name, address as Address, jsondata as CustomData FROM data_table";

    if($result=mysqli_query($con, $sql))
    {
        while($row = mysqli_fetch_array($result))
        {
            $row[2] = json_decode($row[2]);
            $ResultArray[] = $row;
        }   
    }
    return $ResultArray;
}

【讨论】:

  • 完美!我最终这样做了。非常感谢
猜你喜欢
  • 2015-09-14
  • 2015-03-07
  • 1970-01-01
  • 2014-04-24
  • 1970-01-01
  • 1970-01-01
  • 2018-02-28
相关资源
最近更新 更多