LINQ
In Newtonsoft library object can be iterated using LINQ. In this article we will see how we can deserialize json and put LINQ to get specific records. I have taken list of employees with empCode starting 1000 to 1100 and would put filter to get employee within a code range using LINQ C#.
Prerequisites
- Visual Studio 2015 or higher
- Newtonsoft library
Import
using Newtonsoft.Json.Linq;
Create a map “CityDetail“
public class CityDetail{ string Country {get;set;} string CityName {get;set;} string CityArea {get;set;} string Coordinates {get;set;} DateTime RecordDate {get;set;} }
Code example
string oJason=@"[ { 'country':'US', 'cities':{ 'name':'Washington', 'area": '1200Acr', 'coordinates': '1.2.3.4' }, 'recordDate': '2010-07-13T17:11:04' } ]"; //Parase string into array JArray objArray = JArray.Parse(oJason); //Create list with Linq IList<CityDetail> oCity = objArray.Select(p => new CityDetail { Country = (string)p["country"], CityName = (string)p["cities"]["name"], CityArea = (string)p["cities"]["area"], Coordinates = (string)p["cities"]["coordinates"], RecordDate=(DateTime)p["recordDate"] }).ToList(); Console.WriteLine(oCity[0].CityName);
Next >> Create Json using JTokeWriter C# code example