.Net Linq for JSON with the Newtonsoft JSON Library

I have JSON that is sent to my web service that looks something like this.

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

Let's say I wanted to return the value val, where keyis equal "dataid". How can I do this using the JSON.Net library ?

I know that I can iterate over values ​​to find them, but it is likely that the object will be much larger than this example here.

Thanks in advance

+4
source share
2 answers

, - - . JSON, , , Dictionary<string, string> - , ( , LINQ ToDictionary), .

:

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

, :

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);

LINQ-y, , LINQ to JSON.

+7

All Articles