Querying JSON With LINQ
Querying JSON With LINQ
com
The simplest way to get a value from LINQ to JSON is to use the Item[Object] index on
JObject/JArray and then cast the returned JValue to the type you want.
JObject/JArray can also be queried using LINQ. Children() returns the children values of a
JObject/JArray as an IEnumerable<JToken> that can then be queried with the standard
Where/OrderBy/Select LINQ operators.
Note
Children() returns all the children of a token. If it is a JObject it will return a collection of
properties to work with, and if it is a JArray you will get a collection of the array's values.
var postTitles =
from p in rss["channel"]["item"]
select (string)p["title"];
var categories =
from c in rss["channel"]["item"].SelectMany(i =>
i["categories"]).Values<string>()
group c by c
into g
orderby g.Count() descending
select new { Category = g.Key, Count = g.Count() };
LINQ to JSON can also be used to manually convert JSON to a .NET object.
Manually serializing and deserializing between .NET objects is useful when you are working
with JSON that doesn't closely match your .NET objects.
Console.WriteLine(shortie.Original);
Console.WriteLine(shortie.Error.ErrorMessage);
See Also