.Net Linq to JSON with Newtonsoft JSON library

╄→尐↘猪︶ㄣ 提交于 2019-12-20 15:09:10

问题


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


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/5033178/net-linq-to-json-with-newtonsoft-json-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!