首页 > 解决方案 > 强制 Json 属性合并到列表/数组中

问题描述

我得到了一个具有以下结构的 JsonFile(我对德国名字感到抱歉):

"400161": {
"feuerwehrnummer": "someRandomIntagere",
"feuerwehrname": "someCharacters",
"feuerwehrkommandant": {
  "name": "someonesName",
  "dienstgrade": {
    "0": "aa",
    "1": "bb",
    "2": "cc"
  },
  "foto": "fotoPath"
}
"fahrzeuge": {
  "0": {
    "klasse3typ": "L\u00f6schfahrzeuge (B1)",
    "kurzbezeichnung": "LF",
    "name": "PUMPE 2",
    "funkrufname": "PUMPE 2"
  },
  "1": {
    "klasse3typ": "L\u00f6schfahrzeuge (B1)",
    "kurzbezeichnung": "LF",
    "name": "PUMPE 1",
    "funkrufname": "PUMPE 1"
  },
}},

我尝试用 JToken.ToObject-Function 解析它,其中 T 是这个对象:

    public int feuerwehrnummer { get; set; }
    public string feuerwehrname { get; set; }
    public string bezirk { get; set; }
    public string abschnitt { get; set; }
    public string gemeinde { get; set; }
    public firefighterPerson feuerwehrkommandant { get; set; }
    public firefighterPerson abschnittskommdandant { get; set; }
    public firefighterPerson bezirkskommandant { get; set; }
    public firefighterPerson landeskommandant { get; set; }
    public int anzahlfeuerwehren_gemeinde { get; set; }
    public int anzahlfeuerwehren_ff_bezirk { get; set; }
    public int anzahlfeuerwehren_btf_bezirk { get; set; }
    public int anzahlfeuerwehren_bf_bezirk { get; set; }
    public List<fireVehicle> fahrzeuge { get; set; }
    public fotoObject foto { get; set; }

我的问题发生在其后代“dienstgrade”处名为“feuerwehrkommandant”的属性上,因为我试图将其所有后代合并到一个列表中,如下所示:

    class firefighterPerson
{
    public string name { get; set; }

    public List<string> dienstgrade{ get; set; }

    public string foto { get; set; }
}

运行程序时,我收到此错误消息:

不是像整数这样的原始类型,不是像数组或列表这样的集合类型)可以从 JSON 对象反序列化。JsonObjectAttribute 也可以添加到类型中以强制它从 JSON 对象反序列化。路径“400161.feuerwehrkommandant.dienstgrade.0”。

(当然,它也出现在令牌“fahrzeuge”上)

我完全理解该消息,但由于我从中获取数据的 api 不使用 JsonArray,而是使用动态名称(“1”、“2”、...)的属性,所以我没有找到工作的方法围绕这个。有什么办法可以告诉反序列化器将属性合并到一个列表中,还是我必须手动编写反序列化?

标签: c#jsonjson.net

解决方案


Dictionary<string, string> dienstgrade { get; set; }

推荐阅读