Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 425
A. Silva Avatar asked Jun 22 '17 14:06

A. Silva


People also ask

How do I deserialize a JSON file?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

What does Jsonconvert DeserializeObject do?

DeserializeObject Method. Deserializes the JSON to a . NET object.

What is serialized and deserialized in JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).

What is a JSON fragment?

A JSON fragment is a JSON that does not have an Object or an Array as the root. If you do need the ability to encode JSON Fragments, you can change the jsonString function to handle the fragment cases in a different way: The function now encodes JSON fragments as simple strings.


4 Answers

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.

like image 54
Bhadhri Vishal Kannan Avatar answered Oct 13 '22 05:10

Bhadhri Vishal Kannan


If the intend is to deserialize only one property, I generally perefer to use JsonPath due to its flexibility. Please check the code below

var jsonQueryString = "{ 'firstName': 'John',
 'lastName' : 'doe',
 'age'      : 26,}";
JObject o = JObject.Parse(jsonQueryString);
JToken token= o.SelectToken("$.age");   
Console.WriteLine(token);

If your Json is complex, you can use power of JsonPath. you can check https://support.smartbear.com/readyapi/docs/testing/jsonpath-reference.html#examples for JsonPath detailed documentation and examples.

I also included example below for further usage information:

JObject o = JObject.Parse(@"{
        'store': {
            'book': [
            {
                'category': 'history',
                'author': 'Arnold Joseph Toynbee',
                'title': 'A Study of History',
                'price': 5.50
            },
            ...
            ]
        },
        'expensive': 10
        }");
        //gets first book object
        Console.WriteLine(o.SelectToken("$..book[0]"));
        //get first book's title
        Console.WriteLine(o.SelectToken("$..book[0].title"));

        // get authors of the books where the books are cheaper then 10 $
        foreach (var token in o.SelectTokens("$..[?(@.price < 10)].author"))
            Console.WriteLine(token);
like image 32
Derviş Kayımbaşıoğlu Avatar answered Oct 13 '22 03:10

Derviş Kayımbaşıoğlu


If you do not use Newtonsoft and are using System.Text.Json in .NET Core, you can use this:

var post = JsonDocument.Parse(stringifiedJson);
var cat = post.RootElement.GetProperty("category").GetString();

You see GetString here to cast the value to string, there are other overloads available to cast the json value to Int32 etc.

like image 6
Hamid Mosalla Avatar answered Oct 13 '22 05:10

Hamid Mosalla


.NET 5+

The solution is very simple:

using System.Text.Json;

var doc = JsonDocument.Parse(response.Content);
var popupJson= doc.RootElement.GetProperty("menu").GetProperty("popup");
like image 4
user3292624 Avatar answered Oct 13 '22 05:10

user3292624