【发布时间】:2021-12-16 09:48:05
【问题描述】:
鉴于我有这样的 JSON:
[
{
"ct_IncludeinSummary": true,
"ct_allocationid": "12345",
"allocationclassname": "group1",
"allocationname": "name1",
"opendate": "2018-12-30T05:00:00",
"closeddate": null,
"yearendvalue": 2863.93,
"qrgendvalue": 2.06,
"ct_risk": 2
},
{
"ct_IncludeinSummary": true,
"ct_allocationassetid": "5678",
"allocationclassname": "group2",
"allocationname": "name2",
"opendate": "2018-12-30T05:00:00",
"closeddate": null,
"yearendvalue": 13538223.76,
"qrgendvalue": 17337143.84,
"ct_risk": 3
},
{
"ct_IncludeinSummary": true,
"ct_allocationassetid": "89012",
"allocationclassname": "group3",
"allocationname": "name3",
"opendate": "2019-11-18T05:00:00",
"closeddate": null,
"yearendvalue": 0.0,
"qrgendvalue": 561480.62,
"ct_risk": 5
}
]
我可以将结果反序列化为已定义的模型,并且效果很好。
var summaryConciseData = JsonConvert.DeserializeObject<List<SummaryConciseData>>(jsonresult);
public class Summaryconcisedata
{
public Summaryconcisedata(
bool ct_IncludeinSummary,
string ct_allocationassetid,
string allocationclassname,
string allocationname,
DateTime opendate,
DateTime? closeddate,
double? yearendvalue,
double? qrgendvalue,
int ct_risk
)
{
this.IncludeinSummary = ct_IncludeinSummary;
this.allocationid = ct_allocationassetid;
this.allocationclassname = allocationclassname;
this.allocationname = allocationname;
this.opendate = opendate;
this.closeddate = closeddate;
this.yearendvalue = yearendvalue;
this.qrgendvalue = qrgendvalue;
this.risk = risk;
}
public bool IncludeinSummary { get; }
public string allocationid { get; }
public string allocationclassname { get; }
public string allocationname { get; }
public DateTime opendate { get; }
public DateTime? closeddate { get; }
public double? yearendvalue { get; }
public double? qrgendvalue { get; }
public int risk { get; }
}
我想要做的是拥有大量的类(总共大约 30 个)我可以反序列化并加载到模型中
var summaryConciseData = JsonConvert.DeserializeObject(jsonresult, Type.GetType("API.HelperClass.SummaryConciseData"));
我收到以下错误:
无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型 'API.HelperClass.SummaryConciseData',因为该类型需要 JSON 对象(例如 {"name":"value"})才能正确反序列化.
知道我如何成为List<> 吗?
我已经解决了几乎所有类似的问题,但没有一个是指列表中的任何数据
【问题讨论】:
-
你应该做你自己的方法或使用IEnumerable。或者你自己的对象,里面有一个 List 的属性。
标签: c# json deserialization