首页 > 解决方案 > 反序列化 json 数组时出错

问题描述

我正在尝试反序列化 Json 字符串。

这是我的代码:

[System.Serializable]
public class SharedWorlds
{
    public int worldId { get; set; }
    public System.DateTime uploaded { get; set; }
    public string username { get; set; }
    public string levelName { get; set; }
    public string gameVersion { get; set; }
    public string description { get; set; }
    public string filename { get; set; }
    public string screenshot1 { get; set; }
    public string screenshot2 { get; set; }
    public string userTag { get; set; }
    public string userURL { get; set; }
    public double price { get; set; }
    public int    nrDownload { get; set; }
    public int    votes { get; set; }
}
[System.Serializable]
public class Record {
    public List<SharedWorlds> record;
}

    try {
        SDE3D _webService = new SDE3D();
        result= _webService.GetMassiveWorldsList ();

        var records = JsonUtility.FromJson<Record>(result);
    }
    catch(System.Exception ex) {
        Debug.Log (ex.Message.ToString ());
    }

这是我的有效 json(这里有两条记录,但我想每次发送许多记录)。

[
  {
    "worldId": 5,
    "uploaded": "/Date(1524875719000)/",
    "username": "quik",
    "levelName": "Station",
    "gameVersion": "1.0.1",
    "description": "iwoeijksf",
    "filename": "0000003.dat",
    "screenshot1": "0000003a.png",
    "screenshot2": "0000003b.png",
    "userTag": "",
    "userURL": "",
    "price": 0,
    "nrDownload": 5,
    "votes": 5
  },
  {
    "worldId": 4,
    "uploaded": "/Date(1524875659000)/",
    "username": "aksio",
    "levelName": "Garage",
    "gameVersion": "1.0.1",
    "description": "Adlkld",
    "filename": "0000003.dat",
    "screenshot1": "0000003a.png",
    "screenshot2": "0000003b.png",
    "userTag": "",
    "userURL": "",
    "price": 0,
    "nrDownload": 4,
    "votes": 4
  }  
]

我收到错误:

“ArgumentException:JSON 必须表示对象类型。”

我很确定错误在此代码行中:

var records = JsonUtility.FromJson<Record>(result);

如何反序列化 json 对象数组?

谢谢

标签: c#jsonweb-servicesunity3ddeserialization

解决方案


因为您的 JSON 数据不是Record. 这是一个s的集合SharedWorld所以是这样的:

var sharedWorlds = JsonUtility.FromJson<SharedWorld[]>(result);

也许:

var sharedWorlds = JsonUtility.FromJson<List<SharedWorld>>(result);

您可以从中创建一个Record

var record = new Record { record = sharedWorlds };

如果 JSON 需要反序列化为 aRecord那么它需要采用Record对象的格式:

{
    "record": 
    [
        /* the rest of your JSON within the square brackets */
    ]
}

那么它将是Record

var record = JsonUtility.FromJson<Record>(result);

*旁注:您的类和变量名称以及您使用的复数形式确实令人困惑。其语义可能不会让您的调试变得更容易。


推荐阅读