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
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"]);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With