使用LitJson在C#中反序列化JSON对象数组

时间:2011-02-09 20:40:57

标签: c# json serialization unity3d litjson

我受限于Unity3d使用LitJson进行Web Player应用程序的3个新安全措施,否则无法编译。

是否有一种简单的方法将此输出序列化为对象(userEcoGet.text的内容):

{"building_id":"1","building_level":"0","workers":"0","building_health":"100"}{"building_id":"2","building_level":"0","workers":"0","building_health":"100"}...{"building_id":"32","building_level":"0","workers":"0","building_health":"100"}

此代码仅从JSON输入第一个对象:

using UnityEngine;
using System.Collections;
using LitJson;
...
public EcoData localEcoData;
...
localEcoData = JsonMapper.ToObject<EcoData>(userEcoGet.text);
...
public class EcoData
{
    public string building_id;
    public string building_level;
    public string workers;
    public string building_health;
}

将localEcoData转换为数组会导致缺少构造函数错误。我只是不知道如何在这种情况下正确地嵌套构造函数,甚至不确定它是否会有所帮助。

此时我正在使用JsonReader并手动填充对象。任何帮助,将不胜感激。谢谢。

编辑: 这只是疯了,今天全天都被杀了,因为我给自己造成了糟糕的JSON格式......

现在这很好用,localEcoData [1,2 ... 32]是一个可以访问所有元素的对象数组:

public EcoData[] localEcoData;
...
localEcoData = JsonMapper.ToObject<EcoData[]>(userEcoGet.text);

我所要做的就是在PHP页面上正确地编写JSON,它处理MySql并以有序的方式传回Unity。我没有使用数组进行传输而直接回应。现在输出看起来像这样,效果很好:

[{"building_id":"1","building_level":"0","workers":"0","building_health":"100"}{"building_id":"2","building_level":"0","workers":"0","building_health":"100"}...{"building_id":"32","building_level":"0","workers":"0","building_health":"100"}]

谢谢,伙计!

1 个答案:

答案 0 :(得分:1)

我怀疑问题出在您的JSON身上。它的格式不正确。要将其解析为JSON数组,您需要将其格式化为:

{
    result:[
                {"building_id":"1","building_level":"0","workers":"0","building_health":"100"},
                {"building_id":"2","building_level":"0","workers":"0","building_health":"100"},...
                {"building_id":"32","building_level":"0","workers":"0","building_health":"100"}
           ]
}

如果您对JSON没有控制权,那么您可能需要拆分字符串并将每个字符串视为单个JSON对象,并将数组中的每个元素转换为C#对象类型。