Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you parse an array of objects with Newtonsoft?

I just want to get this JSON into some kind of an object. JArray and JToken are completely confusing to me.

I can create a class so that Newtonsoft knows what to map to but if you will notice the objects have the structure of: { "anAnimal": { foo: 1, bar: 2 }} and idk what that mapper object will look like. I’m pretty sure this should just work instantly with zero thought on my part.

var myFavoriteAnimalsJson = @"
[
    {
        ""Dog"": {
            ""cuteness"": ""7.123"",
            ""usefulness"": ""5.2"",
        }
    },
    {
        ""Cat"": {
            ""cuteness"": ""8.3"",
            ""usefulness"": ""0"",
        }
    }
]";

var jArray = new JArray(myFavoriteAnimalsJson);
// grab the dog object. or the cat object. HOW CUTE IS THE DOG? 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

With .SelectToken() to construct the JSON path query logic.

The below sample to query the first item of animals to get the object of "Dog" token and its value.

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

JArray animals = JArray.Parse(myFavoriteAnimalsJson);
        
var dog = animals[0].SelectToken("Dog");

Console.WriteLine(dog);
Console.WriteLine(dog["cuteness"]);

Sample Program

Output

{
"cuteness": "7.123",
"usefulness": "5.2"
}

7.123

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading