我正在尝试反序列化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对象数组?
由于
答案 0 :(得分:3)
因为您的JSON数据不是Record
。它是SharedWorld
的集合。所以像这样:
var sharedWorlds = JsonUtility.FromJson<SharedWorld[]>(result);
或者也许:
var sharedWorlds = JsonUtility.FromJson<List<SharedWorld>>(result);
您可以从中创建Record
:
var record = new Record { record = sharedWorlds };
如果JSON需要反序列化为Record
,那么它需要采用Record
对象的格式:
{
"record":
[
/* the rest of your JSON within the square brackets */
]
}
然后它将是Record
:
var record = JsonUtility.FromJson<Record>(result);
*附注:您的类和变量名以及您正在使用的复数确实令人困惑。其语义可能不会让您的调试更容易。
答案 1 :(得分:-2)
您可以编写JSON
中没有任何一个对象的对象集合