【问题标题】:How can I deserialize a specific JSON object?如何反序列化特定的 JSON 对象?
【发布时间】:2019-02-25 20:22:30
【问题描述】:

我正在尝试序列化我认为是 .NET Core 2.2 应用程序中不寻常的 JSON 结构。

{
    "id": "002a40a1-2e31-4663-a8d0-a4e6e2742d62",
    "data": [
        1,
        [
            "value",
            false
        ]
    ]
}

当我尝试在 c# 中对数据属性建模时,我感到困惑

public class DataItem {
    [JsonProperty("id")]
    string id;

    [JsonProperty("data")]
    public object[] data;
}

我不知道如何在 C# 中正确建模此结构以允许 Newtonsoft 对其进行反序列化。

【问题讨论】:

  • 使用属性而不是字段

标签: c# json .net-core json.net


【解决方案1】:

由于它没有结构化格式,我建议你使用dynamic。或者如果您使用object[],您可以手动迭代每个对象并检查 if 条件内的对象类型。

您也可以使用IDictionary<string, JToken>

public class DataItem {
    [JsonProperty("id")]
    string id;

    [JsonProperty("data")]
    public Dictionary<string, JToken> data;
}

【讨论】:

    【解决方案2】:

    如果您不知道运行时的数据是什么,则必须使用 JsonExtensionDataAttribute

    所以它会将你的“数据”抽象成 JToken 的字典

    public class DataItem {
        [JsonProperty("id")]
        string id;
    
        [JsonProperty("data")]
        [JsonExtensionData]
        public IDictionary<string, JToken> data;
    }
    

    您可以在此处查看更多详细信息:https://www.jerriepelser.com/blog/using-jsonextensiondata-with-jsonnet/https://www.newtonsoft.com/json/help/html/SerializationAttributes.htm

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-01
      • 2013-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-10
      • 1970-01-01
      相关资源
      最近更新 更多