How do you parse an array of objects with Newtonsoft?

Advertisements

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? 

>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

Leave a ReplyCancel reply