如何在运行时将类名传递给 JSON DeserializeObject?
Posted
技术标签:
【中文标题】如何在运行时将类名传递给 JSON DeserializeObject?【英文标题】:How to pass class name to JSON DeserializeObject at runtime? 【发布时间】: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 的属性。 这里有一些想法thecodebuzz.com/deserialize-json-into-type-object-dynamically 可能有用。 【参考方案1】:MakeGenericType
在 list/ienumerable 类型上应该可以正常工作:
var listType = typeof(List<>).MakeGenericType(Type.GetType("API.HelperClass.SummaryConciseData");
var summaryConciseData = JsonConvert.DeserializeObject(jsonresult, listType);
【讨论】:
好吧,我应该在两天前问这个问题。就像那样,就像一个魅力。谢谢!以上是关于如何在运行时将类名传递给 JSON DeserializeObject?的主要内容,如果未能解决你的问题,请参考以下文章
向 nodemon 注册时将 --project 传递给 ts-node
在页面加载时将道具传递给子组件 - 与 next.js 做出反应