Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Linq to JSON with Newtonsoft JSON library

I have some JSON that is sent to my webservice that looks something like this.

{
    root: [
        {
            "key": "foo1",
            "val": "150"
        },
        {
            "key": "foo2",
            "val": "220"
        },
        {
            "key": "foo3",
            "val": "300"
        },
        {
            "key": "dataid",
            "val": "2289"
        }
    ]
}

Say I wanted to return the value of val where key is equal to "dataid". How would I do this using the JSON.Net library?

I know I can loop through the values to find it but it is likely that the object will be far bigger than this example here.

Thanks in advance

like image 679
CResults Avatar asked Nov 29 '22 03:11

CResults


1 Answers

Well something is going to have to loop through at some point. If you need to fetch lots of values by key from the same JSON, you should probably build a Dictionary<string, string> from it - which means looping over it once (either explicitly or using the LINQ ToDictionary method) but then having fast access afterwards.

Here's some sample code:

using System;
using System.IO;
using System.Linq;

using Newtonsoft.Json.Linq;

class Test
{
    static void Main()
    {
        string text = File.ReadAllText("test.json");
        JObject obj = JObject.Parse(text);
        JArray root = (JArray) obj["root"];

        var dictionary = root.ToDictionary(x => (string) x["key"],
                                           x => (string) x["val"]);

        Console.WriteLine(dictionary["dataid"]);
    }
}
like image 154
Jon Skeet Avatar answered Dec 10 '22 20:12

Jon Skeet