c# - 反序列化 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 对象数组?
谢谢
解决方案
因为您的 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);
*旁注:您的类和变量名称以及您使用的复数形式确实令人困惑。其语义可能不会让您的调试变得更容易。
推荐阅读
- firebase - 在 initState() 中放置两个 Firestore.instances
- python - 不断收到 UnboundLocalError 错误:分配前引用的局部变量 'batch_index'
- unity3d - 爆炸动画播放时位置不对
- python - 如何在熊猫中一次重新分配多个 MultiIndex 列?
- python - 使用熊猫,在将每个连续值与前一个值进行比较时,遍历数据框中的列的最佳方法是什么
- list - 使用回归量列表并存储 beta 值
- java - 无法使用 Spring Boot 将 Node 保存到 Neo4j
- mongodb - Springboot mongo异常与Docker
- javascript - jquery 函数总是跳过表单验证
- tableau-api - Tableau 数据层仅转换为一种状态