Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
567 views
in Technique[技术] by (71.8m points)

c# - Deserialize only one property of a JSON file

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...