CResults
CResults

Reputation: 5105

.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

Upvotes: 4

Views: 18609

Answers (2)

Daniel T.
Daniel T.

Reputation: 38370

Jon beat me to it, but here's another way of doing it:

var json = File.ReadAllText("data.json");
var jobject = JObject.Parse(json);

var item = jobject.Property("root")
                  .Values()
                  .Single(x => x.Value<string>("key") == "foo1");

var value = item.Value<string>("val");

Console.WriteLine(value);

Slightly more LINQ-y, but there's no way of really getting rid of the magic strings if you use LINQ to JSON.

Upvotes: 8

Jon Skeet
Jon Skeet

Reputation: 1499760

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"]);
    }
}

Upvotes: 18

Related Questions