c# json转换错误
本文关键字:错误 转换 json | 更新日期: 2023-09-27 18:03:26
我有这个Json返回:
[
{
"url": "http://xxx.xxx.xxx",
"code": 0,
"aplication":
{
"version":
[
{
"silent": true,
"checksum": "9aabad09b09459ac6c9e54f9ca4eb5c4",
"size": 1250619,
"force": true,
"apply_message": "",
"id": 116,
"id_aplication": 4,
"number": "1.0.5.0",
"news": "",
"automatic": true,
"installation": "Setup.exe"
}
],
"division_name": "DNT",
"app_name": "MyApplication",
"id": 4,
"id_master": 0
},
"message": "New Application Found"
}
]
使用这个站点http://json2csharp.com/,我生成了这些类:
public class Version
{
public bool silent { get; set; }
public string checksum { get; set; }
public int size { get; set; }
public bool force { get; set; }
public string apply_message { get; set; }
public int id { get; set; }
public int id_aplication { get; set; }
public string number { get; set; }
public string news { get; set; }
public bool automatic { get; set; }
public string installation { get; set; }
}
public class Aplication
{
public List<Version> version { get; set; }
public string division_name { get; set; }
public string app_name { get; set; }
public int id { get; set; }
public int id_master { get; set; }
}
public class RootObject
{
public string url { get; set; }
public int code { get; set; }
public Aplication aplication { get; set; }
public string message { get; set; }
}
然后,在我的c#代码中,我这样写:
RootObject test = JsonConvert.DeserializeObject<RootObject>(jsonResult);
但是,我收到这个错误:
不能反序列化当前JSON对象(例如{"name":"value"})into type 'System.Collections.Generic.List ' 1[consoleapp . application]'因为该类型需要一个JSON数组(例如[1,2,3])来反序列化正确。要修复此错误,可以将JSON更改为JSON数组(例如[1,2,3])或更改反序列化类型,使其为正常类型.NET类型(例如,不是像整数这样的原始类型,也不是集合)类型(如数组或列表),可以从JSON中反序列化对象。还可以将JsonObjectAttribute添加到类型中以强制使用它从JSON对象反序列化。路径的应用。版本',第一行,位置227 .
我读了一些关于这方面的提示,但对我没有帮助。例如:
无法在WCF REST中解析JSON数组
您的JSON是一个数组-它只包含一个项目,但它仍然是一个数组。如果您从大JSON字符串中删除开头和结尾的[
和]
,它应该可以很好地反序列化。
或者可以反序列化为RootObject[]
而不是RootObject
。