Click or drag to resize
Json.NETQuerying JSON with LINQ
 

LINQ to JSON provides a number of methods for getting data from its objects. The index methods on JObject/JArray let you quickly get data by its property name on an object or index in a collection, while Children lets you get ranges of data as IEnumerable<JToken> to then query using LINQ.

Getting values by Property Name or Collection Index

The simplest way to get a value from LINQ to JSON is to use the ItemObject index on JObject/JArray and then cast the returned JValue to the type you want.

Getting JSON Values
 1string json = @"{
 2  'channel': {
 3    'title': 'James Newton-King',
 4    'link': 'http://james.newtonking.com',
 5    'description': 'James Newton-King's blog.',
 6    'item': [
 7      {
 8        'title': 'Json.NET 1.3 + New license + Now on CodePlex',
 9        'description': 'Annoucing the release of Json.NET 1.3, the MIT license and the source on CodePlex',
10        'link': 'http://james.newtonking.com/projects/json-net.aspx',
11        'categories': [
12          'Json.NET',
13          'CodePlex'
14        ]
15      },
16      {
17        'title': 'LINQ to JSON beta',
18        'description': 'Annoucing LINQ to JSON',
19        'link': 'http://james.newtonking.com/projects/json-net.aspx',
20        'categories': [
21          'Json.NET',
22          'LINQ'
23        ]
24      }
25    ]
26  }
27}";
28
29JObject rss = JObject.Parse(json);
30
31string rssTitle = (string)rss["channel"]["title"];
32// James Newton-King
33
34string itemTitle = (string)rss["channel"]["item"][0]["title"];
35// Json.NET 1.3 + New license + Now on CodePlex
36
37JArray categories = (JArray)rss["channel"]["item"][0]["categories"];
38// ["Json.NET", "CodePlex"]
39
40IList<string> categoriesText = categories.Select(c => (string)c).ToList();
41// Json.NET
42// CodePlex
Querying with LINQ

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 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.

Querying JSON
 1var postTitles =
 2    from p in rss["channel"]["item"]
 3    select (string)p["title"];
 4
 5foreach (var item in postTitles)
 6{
 7    Console.WriteLine(item);
 8}
 9
10//LINQ to JSON beta
11//Json.NET 1.3 + New license + Now on CodePlex
12
13var categories =
14    from c in rss["channel"]["item"].Children()["category"].Values<string>()
15    group c by c
16    into g
17    orderby g.Count() descending
18    select new { Category = g.Key, Count = g.Count() };
19
20foreach (var c in categories)
21{
22    Console.WriteLine(c.Category + " - Count: " + c.Count);
23}
24
25//Json.NET - Count: 2
26//LINQ - Count: 1
27//CodePlex - Count: 1

LINQ to JSON can also be used to manually convert JSON to a .NET object.

Deserializing Using LINQ Objects
 1public class Shortie
 2{
 3    public string Original { get; set; }
 4    public string Shortened { get; set; }
 5    public string Short { get; set; }
 6    public ShortieException Error { get; set; }
 7}
 8
 9public class ShortieException
10{
11    public int Code { get; set; }
12    public string ErrorMessage { get; set; }
13}

Manually serializing and deserializing between .NET objects is useful when you are working with JSON that doesn't closely match your .NET objects.

Deserializing Using LINQ Example
 1string jsonText = @"{
 2  'short': {
 3    'original': 'http://www.foo.com/',
 4    'short': 'krehqk',
 5    'error': {
 6      'code':0,
 7      'msg':'No action taken'
 8    }
 9}";
10
11JObject json = JObject.Parse(jsonText);
12
13Shortie shortie = new Shortie
14{
15    Original = (string)json["short"]["original"],
16    Short = (string)json["short"]["short"],
17    Error = new ShortieException
18    {
19        Code = (int)json["short"]["error"]["code"],
20        ErrorMessage = (string)json["short"]["error"]["msg"]
21    }
22};
23
24Console.WriteLine(shortie.Original);
25// http://www.foo.com/
26
27Console.WriteLine(shortie.Error.ErrorMessage);
28// No action taken
See Also