Json.Net 映射到字典或其他一些

本文关键字:其他 字典 Net 映射 Json | 更新日期: 2023-09-27 18:30:56

给定这个 Json:

{
    "id": "1",
    "fields": [
        "a",
        "b",
        "c"
    ],
    "otherfields": [
        "n"
    ],
    "collection": {
        "element1": [
            {
                "7": {
                    "sub_id": "7",
                    "sub_name": "SN7"
                },
                "9": {
                    "sub_id": "9",
                    "sub_name": "SN9"
                }
            }
        ]
    }
}

并给定以下类:

public class Element
{
    [JsonProperty("sub_id")]
    public string SubId { get; set; }
    [JsonProperty("sub_name")]
    public string SubName { get; set; }
}
public class Element1
{
    [JsonProperty(?)] // <"7", Element> and <"9", Element> ???
    public IDictionary<String, Element> Elements { get; set; }
}
public class Collection
{
    [JsonProperty("element1")]
    public IList<Element1> Element1 { get; set; }
}
public class Example
{
    [JsonProperty("id")]
    public string Id { get; set; }
    [JsonProperty("fields")]
    public IList<string> Fields { get; set; }
    [JsonProperty("otherfields")]
    public IList<string> Otherfields { get; set; }
    [JsonProperty("collection")]
    public Collection Collection { get; set; }
}

是否有可能(以及如何?)将 json 对象解救到我给定的类中? 或者,也许是将 JSON 对象映射到另一个结构类的最佳方法?

提前谢谢你。

Json.Net 映射到字典或其他一些

你不需要 Element1 - json 中的 element1 属性是一个包含字典的数组。

public class Collection
{
    [JsonProperty("element1")]
    public IList<IDictionary<String, Element>> Element1 { get; set; }
}