Deserializing just a single node of a JSON response

点点圈 提交于 2019-12-20 04:52:40

问题


I have a json response like

{
  "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"
  }
}

Using json.NET, I want to extract configResponse into dictionary. I know i can directly convert a Dictionary object like this

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

but since configResponse is a sub element, I am not able to parse it as required.

I want to deserialize the above json response as

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; }
}

回答1:


You can parse JSON string into JObject, get sub-object "configResponse", then deserialize it into ConfigResponse. It's one line of code:

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

If you need a custom serializer to set deserialization options, you can pass it to ToObject<T>() method.




回答2:


i have only use this method and it worked.

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


来源:https://stackoverflow.com/questions/17502606/deserializing-just-a-single-node-of-a-json-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!