如何在运行时将 class 名称传递给 JSON DeserializeObject?

How to pass class name to JSON DeserializeObject at runtime?

鉴于我有 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"));

我收到以下错误:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'API.HelperClass.SummaryConciseData' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

知道如何将它变成 List<> 吗? 我已经解决了大部分类似的问题,但 none 指的是列表

中的任何数据

MakeGenericType 在 list/ienumerable 类型上应该可以正常工作:

var listType = typeof(List<>).MakeGenericType(Type.GetType("API.HelperClass.SummaryConciseData");
var summaryConciseData = JsonConvert.DeserializeObject(jsonresult, listType);