【问题标题】:Deserializing just a single node of a JSON response仅反序列化 JSON 响应的单个节点
【发布时间】:2013-07-04 08:48:18
【问题描述】:

我有一个像

这样的 json 响应
{
  "appStatus":{
    "status":true
  },
  "lastSyncDate":"06-07-2013 13.54.27",
  "configResponse":{
    "status":{
      "status":true
    },
    "configs":{
      "APPLOGENABLED":{
        "configCode":"APPLOGENABLED",
        "configDesc":"enable or disable logging from front end",
        "configType":"TAB",
        "configValue":"Y"
      },
      "COMMENTSTIMER":{
        "configCode":"COMMENTSTIMER",
        "configDesc":"timer for comments in seconds",
        "configType":"TAB",
        "configValue":"60"
      },
      "SUMMARYTIMER":{
        "configCode":"SUMMARYTIMER",
        "configDesc":"timer for summary in seconds",
        "configType":"TAB",
        "configValue":"30"
      },
      "ALERTSTIMER":{
        "configCode":"ALERTSTIMER",
        "configDesc":"timer for alerts in seconds",
        "configType":"TAB",
        "configValue":"60"
      }
    },
    "lastSyncDate":"06/07/2013 13.48.13"
  }
}

使用 json.NET,我想将configResponse 提取到字典中。我知道我可以像这样直接转换 Dictionary 对象

  JsonConvert.DeserializeObject<Dictionary<string,string>>().... 

但由于configResponse 是一个子元素,我无法按要求解析它。

我想将上面的json响应反序列化为

public class ConfigResponse
{
    public Status status { get; set; }
    public Dictionary<string, ConfigurationItem> configs { get; set; }
    public string lastSyncDate { get; set; }
}

public class ConfigurationItem
{
    public String configCode { get; set; }
    public String configDesc { get; set; }
    public String configType { get; set; }
    public String configValue { get; set; }
}

【问题讨论】:

  • 能否添加完整代码以便更好地理解

标签: c# .net json dictionary json.net


【解决方案1】:

您可以将 JSON 字符串解析为JObject,获取子对象“configResponse”,然后将其反序列化为ConfigResponse。就一行代码:

JObject.Parse("{...}")["configResponse"].ToObject<ConfigResponse>()

如果您需要自定义序列化程序来设置反序列化选项,可以将其传递给ToObject&lt;T&gt;() 方法。

【讨论】:

    【解决方案2】:

    我只用过这个方法,效果很好。

     await JsonConvert.DeserializeObjectAsync<ConfigResponse>(jsontoobject, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
    

    【讨论】:

    • 对不起,但这甚至不能解决您自己的问题。另外,您甚至没有提到jsontoobject 是什么。另一个答案应该是公认的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多