LINQ is used for querying collections in .NET.There are different LINQ providers for querying different data sources.For example if you want to query SQL then you use LINQ to SQL.When working with JSON you can use LINQ to JSON.It is not a LINQ provider but an API which allows working with JSON objects in C#.It is part of JSON.NET framework which provides JSON support in .NET.
Following steps could be used for querying JSON :
-
Install Netwonsoft.Json using nuget package manager or package manager console.
If you are using package manager console then
you can use the following command:
Install-Package Newtonsoft.Json
import the JSON.NET namespaces
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
2. Parse the JSON string using the Parse method of JObject class.
This method will return an object representing the JSON string
JObject.Parse(“JSON String”)
3. Now you can query the JSON object using the linq query
In the following example Employee class is declared.
public class Employee { public int ID { get; set; } public string Name { get; set; } }
then we are fetching the Employee list using the JSON source in DBHelper class as:
public static class DBHelper { public static JObject GetEmployeesJSON() { JObject o = JObject.Parse(@"{ 'Organization': 'MyOrganization', 'Address':'Address', 'Employees': [ {'Name':'1'}, {'Name':'2'} ] }"); return o; } }
Now you can get the Employee list as:
var employees= DBHelper.GetEmployeesJSON()["Employees"].Select(emp =>emp).ToList();
LINQ to JSON provides the following useful classes
- JObject
- JArray
- JProperty
Children() method returns the children as an IEnumerable<JToken>.It can be used with JObject or JArray
Leave a Reply