问题
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