仅反序列化 JSON 响应的单个节点

Sha*_*ood 2 .net c# json dictionary json.net

我有一个 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"
  }
}
Run Code Online (Sandbox Code Playgroud)

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

  JsonConvert.DeserializeObject<Dictionary<string,string>>().... 
Run Code Online (Sandbox Code Playgroud)

但由于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; }
}
Run Code Online (Sandbox Code Playgroud)

Ath*_*ari 5

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

JObject.Parse("{...}")["configResponse"].ToObject<ConfigResponse>()
Run Code Online (Sandbox Code Playgroud)

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