【问题标题】:Deserialize JSON from multiple objects to list of objects将 JSON 从多个对象反序列化为对象列表
【发布时间】:2019-11-20 02:16:16
【问题描述】:

无法为从服务接收到的 JSON 响应创建映射对象/响应模型。

尝试创建自定义 JsonConverter 但找不到任何合适的方法来帮助解决反序列化问题

以下是我从服务获得的 JSON 响应。

{
    "$base": "Collection",
    "nodeType": "PROTOCOL",
    "Smart Building 0": {
        "$base": "Collection",
        "nodeType": "NETWORK",
        "truncated": "true"
    },
    "Smart Building 1": {
        "$base": "Collection",
        "nodeType": "NETWORK",
        "truncated": "true"
    },
    "Smart Building 2": {
        "$base": "Collection",
        "nodeType": "NETWORK",
        "truncated": "true"
    }
}

示例 1:- 相同的服务可以返回 JSON 格式以下

{
    "$base": "Collection",
    "nodeType": "PROTOCOL",
    "Smart Building 0": {
        "$base": "Collection",
        "nodeType": "NETWORK",
        "truncated": "true"
    },
    "Smart Building 1": {
        "$base": "Collection",
        "nodeType": "NETWORK",
        "truncated": "true"
    }
}

创建 c# 根对象类,以便它可以轻松用于反序列化 使用 JsonConvert

【问题讨论】:

  • 我你想要做的事情通常会非常困难,因为提供的 JSON 也不是列表格式,而是称为“智能建筑 1”等的单独对象,如果你可以控制的话JSON 是不是更容易重新格式化 JSON 而不是拥有一个复杂的服务器端反序列化器?
  • @NinoMemelink 我同意您提供的建议,但我无法控制从服务发回的 JSON 响应格式...

标签: c# serialization json.net deserialization jsonconvert


【解决方案1】:

试试这个:

public class Root : Dictionary<string, Building>
{   
    [JsonProperty("$base")]
    public string Base { get; set; }

    [JsonProperty("nodeType")]
    public string NodeType { get; set; }
}

public class Building
{
    [JsonProperty("$base")]
    public string Base { get; set; }

    [JsonProperty("nodeType")]
    public string NodeType { get; set; }

    [JsonProperty("truncated")]
    public string Truncated { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    • 2016-05-30
    • 2012-03-07
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多