Using LINQ with Json.NET to query JSON in your C# application
If you're developing for .NET, you might just want to skip JSONPath entirely and use Json.NET's support to subscribe based on field name and support for LINQ. Json.NET supports LINQ out of the box, letting you craft any query you want against your JSON in either fluent or statement syntax.
Getting ready
As with the previous recipe, your .NET project needs to use Json.NET. To include Json.NET in your project, follow the steps I show you in Chapter 7, Using JSON in a Type-safe Manner, in the Getting Started section of the How to Deserialize an Object with Json.NET recipe.
How to do it…
You'll parse the JSON to JObject
, and then you can just evaluate LINQ expressions against the resulting JObject
, like this:
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json.Linq; static void Main(string[] args) { var obj = JObject.Parse(json); var titles = from book in obj["store"]["book"] select (string...