php - 在 PHP 中编码 JSON 时,从数据库中选择的 JSON 字符串最终格式错误

标签 php mysql json mysqli

我有一个数据库,其中有几个简单的文本列和一个列,其中包含一个包含附加数据的 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# 中的错误消息:

Error converting value "[{"CustomDataName":"asdasdasdas","CustomDataLabel":"asdasdasdas","CustomDataValue":"RandomValue...","CustomDataType":"Text","Permission":"1"},...]" to type 'System.Collections.Generic.List`1[NameSpace.myObject]'. Path 'Result[0].CustomData', line 1, position 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 无效,您对“CustomData”进行了编码,然后在最终对象中进行了第二次编码。如果您删除第一个编码操作,一切都会好起来的。 enter image description here

您的 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;
}

关于php - 在 PHP 中编码 JSON 时,从数据库中选择的 JSON 字符串最终格式错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46095448/

相关文章:

php - Mysql根据字段获取三组行

php - JWT Cookie 存储不正确 - Laravel

java - 数据无法正常存入mysql

mysql - 是否可以按升序以外的任何顺序进行分组?

MySQL复制监控

c# - 超出 JavaScriptSerializer maxJsonLength

javascript - jQuery : how to switch case when requesting JSON info

php - memory_get_peak_usage() 与 "real usage"

javascript - 如何获取数据标志的值

javascript - 如何从 extjs 中的 json 为嵌套组合框创建数组