Home > Blockchain >  How do you parse an array of objects with Newtonsoft?
How do you parse an array of objects with Newtonsoft?

Time:05-18

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? 

CodePudding user response:

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

CodePudding user response:

You can deserialize it to a List<Dictionary<string, AnimalData>>

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

var results = JsonConvert.DeserializeObject<List<Dictionary<string, AnimalData>>>(myFavoriteAnimalsJson);

Now each list item contains a dictionary with a single key of Dog Cat...

CodePudding user response:

If you start from a serialized JSON, i.e. a string, you have to parse it:

var jArray = JArray.Parse(myFavoriteAnimalsJson);
  • Related