Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am faced with a problem. I want to deserialize a complex JSON response from a server, but I only need one part of it.

Here is an example:

{
 "menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
 }
}

I also used Csharp2json to get the class objects that I need, I just modified the menu class according to my needs :

    public class Menuitem
{
    public string value { get; set; }
    public string onclick { get; set; }
}

public class Popup
{
    public IList<Menuitem> menuitem { get; set; }
}

public class Menu
{
    public Popup popup { get; set; }
}

public class RootObjectJourney
{
    public Menu menu { get; set; }
}

Now, how do I deserialize if I only need the popup value and his children?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
553 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can actually utilize the Linq namespace of the NewtonSoft.Json and modify your code little bit to get only the "popup" elements from the JSON.

your class structure remains the same. Make sure you use the namespace(s)

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

then in your code once you have the JSON string with you, you can use the "JObject" static method "Parse" to parse the JSON, like

   var parsedObject = JObject.Parse(jsonString);

This will give you the JObject with which you can access all your JSON Keys just like a Dictionary.

var popupJson = parsedObject["menu"]["popup"].ToString();

This popupJson now has the JSON only for the popup key. with this you can use the JsonConvert to de- serialize the JSON.

var popupObj = JsonConvert.DeserializeObject<Popup>(popupJson);

this popupObj has only list of menuitems.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...