Linq to JSON is used to manipulate JSON objects and can be used to quickly query, modify and create JSON objects.
When the content of JSON objects is complex and we only need a small part of the data, we can consider using Linq to JSON to read and modify part of the data instead of deserializing everything.
refer to: Documentation
Before doing Linq to JSON, you must first understand the classes used to operate Linq to JSON.
Class Name | illustrate |
---|---|
JObject | Used to manipulate JSON objects |
JArray | Manipulate JSON arrays in terms of terms |
JValue | Represents the value in the array |
JProperty | Represents the attribute in the object, in the form of "key/value" |
JToken | Used to store the results after Linq to JSON query |
1. Create a JObject and JArrary instance
1. Create JSON manually
Setting values and creating an object or array at a time gives you full control, but it's more verbose than other options.
1. Create JSON object, JObject
JObject staff = new JObject(); (new JProperty("Name", "Jack")); (new JProperty("Age", 33)); (new JProperty("Department", "Personnel Department")); (new JProperty("Leader", new JObject(new JProperty("Name", "Tom"), new JProperty("Age", 44), new JProperty("Department", "Personnel Department")))); (()); //return//{ // "Name": "Jack", // "Age": 33, // "Department": "Personnel Department", // "Leader": { // "Name": "Tom", // "Age": 44, // "Department": "Personnel Department" // } //}
2. Create JSON array, JArrary
JArray arr = new JArray(); (new JValue(1)); (new JValue(2)); (new JValue(3)); (()); //return//[ // 1, // 2, // 3 //]
2. Create JSON using Linq
Creating JSON objects declaratively using LINQ is a quick way to create JSON from a collection of values.
List posts = GetPosts(); JObject rss = new JObject( new JProperty("channel", new JObject( new JProperty("title", "James Newton-King"), new JProperty("link", ""), new JProperty("description", "James Newton-King's blog."), new JProperty("item", new JArray( from p in posts orderby select new JObject( new JProperty("title", ), new JProperty("description", ), new JProperty("link", ), new JProperty("category", new JArray( from c in select new JValue(c))))))))); (()); //{ // "channel": { // "title": "James Newton-King", // "link": "", // "description": "James Newton-King\'s blog.", // "item": [ // { // "title": " 1.3 + New license + Now on CodePlex", // "description": "Announcing the release of 1.3, the MIT license and being available on CodePlex", // "link": "/projects/", // "category": [ // "", // "CodePlex" // ] // }, // { // "title": "LINQ to JSON beta", // "description": "Announcing LINQ to JSON", // "link": "/projects/", // "category": [ // "", // "LINQ" // ] // } // ] // } //}
3. Create JSON from an object
(object o): o is the object to be converted, returning a JObject object
The last option is to create a JSON object from a non-JSON type using the FromObject() method.
The following example shows how to create a JSON object from anonymous object, but any .net type can create a JSON with FromObject.
var posts = new[] { new { Title=" 1.3 + New license + Now on CodePlex", Description= "Announcing the release of 1.3, the MIT license and being available on CodePlex", Link="/projects/", Categories=new[]{ "","CodePlex"} }, new { Title="LINQ to JSON beta", Description= "Announcing LINQ to JSON", Link="/projects/", Categories=new[]{ "","LINQ"} }, }; JObject o = (new { channel = new { title = "James Newton-King", link = "", description = "James Newton-King's blog.", item = //Return to the array from p in posts orderby select new { title = , description = , link = , category = } } }); (()); //{ // "channel": { // "title": "James Newton-King", // "link": "", // "description": "James Newton-King\'s blog.", // "item": [ // { // "title": " 1.3 + New license + Now on CodePlex", // "description": "Announcing the release of 1.3, the MIT license and being available on CodePlex", // "link": "/projects/", // "category": [ // "", // "CodePlex" // ] // }, // { // "title": "LINQ to JSON beta", // "description": "Announcing LINQ to JSON", // "link": "/projects/", // "category": [ // "", // "LINQ" // ] // } // ] // } //}
4. Parsing JSON text
(string json): json contains a string of JSON object, returned as a JObject object
//Parse JSON objectstring json = @"{ CPU: 'Intel', Drives: [ 'DVD read/writer', '500 gigabyte hard drive' ] }"; JObject o = (json); //Parse JSON arraystring json = @"[ 'Small', 'Medium', 'Large' ]"; JArray a = (json);
5. Load JSON from the file
using (StreamReader reader = (@"c:\")) { JObject o = (JObject)(new JsonTextReader(reader)); // do stuff }
2. Use deserialization of JOSN fragments
1. Array data
string jsonArrayText= "[{'a','al'.'b','b1'},{'a','a2'.'b','b2'}]"; JArray ja = (JArray)(jsonArrayText); string ja1a==ja[1]["a"].ToString(); //orJObject o=(JObject)ja[1]; string ja1a=o["a"].ToString();
2. Object format
siring jsonText= "{\"beijing\":{\"zone\":\"Haidian\",\"zone_en\":\"haidian\"}"; JObject jo =(JObject)(jsonArrayText); string zone =jo["beijing"]["zone"].ToString();
3. Modify JObject and JArrary instances
string json = @"{ 'post':{ 'Title':'Modify JArray and JObject', 'Link':'', 'Description':'This is a modificationJArrayandJObjectDemonstration case', 'Item':[] } }"; JObject o = (json); JObject post = (JObject)o["post"]; post["Title"] = ((string)post["Title"]).ToUpper(); post["Link"] = ((string)post["Link"]).ToUpper(); ("Description").Remove(); ("Link").AddAfterSelf(new JProperty("New", "Newly added attribute")); JArray a = (JArray)post["Item"]; ("Modify JArray"); ("Modify JObject");
Remove attributes
JObject jObj = (json); ("Colleagues");//It's following the attribute name(());
4. Query JObject and JArrary instances
The easiest way to convert a value from LINQ to JSON is to use the ItemObject index on JObject/JArray and then convert the returned JValue to the desired type.
string json = @"{ 'channel': { 'title': 'James Newton-King', 'link': '', 'description': 'James Newton-King\'s blog.', 'item': [ { 'title': ' 1.3 + New license + Now on CodePlex', 'description': 'Announcing the release of 1.3, the MIT license and the source on CodePlex', 'link': '/projects/', 'categories': [ '', 'CodePlex' ] }, { 'title': 'LINQ to JSON beta', 'description': 'Announcing LINQ to JSON', 'link': '/projects/', 'categories': [ '', 'LINQ' ] } ] } }"; JObject rss = (json); string rssTitle = (string)rss["channel"]["title"]; // James Newton-King string itemTitle = (string)rss["channel"]["item"][0]["title"]; // 1.3 + New license + Now on CodePlex JArray categories = (JArray)rss["channel"]["item"][0]["categories"]; // ["", "CodePlex"] IList<string> categoriesText = (c => (string)c).ToList(); // // CodePlex
Determine whether the Key exists
JToken test = new JObject(); if (test["a"] == null) { ("The key-value key does not exist!"); } JObject test1 = test as JObject; if (("a") == null || ("a").ToString() == "") { ("The key-value key does not exist!"); }
5. Use LINQ expressions to query
You can also use LINQ to query JObject/JArray.
Children() returns the child values of JObject/JArray in the form of IEnumerable, and these child values can then be queried using the standard Where/OrderBy/Select LINQ operator.
Notice:
Children() returns all child elements of token. If it is a JObject, it will return a collection of properties to use, if it is a JArray, you will get a collection of array values.
var postTitles = from p in rss["channel"]["item"] select (string)p["title"]; foreach (var item in postTitles) { (item); } //LINQ to JSON beta // 1.3 + New license + Now on CodePlex var categories = from c in rss["channel"]["item"].SelectMany(i => i["categories"]).Values<string>() group c by c into g orderby () descending select new { Category = , Count = () }; foreach (var c in categories) { ( + " - Count: " + ); } // - Count: 2 //LINQ - Count: 1 //CodePlex - Count: 1
JSON can be converted manually to .net objects using LINQ to JSON.
Manual serialization and deserialization of .net objects is useful when you deal with JSON that does not match the .net object.
string jsonText = @"{ 'short': { 'original': '/', 'short': 'krehqk', 'error': { 'code': 0, 'msg': 'No action taken' } } }"; JObject json = (jsonText); Shortie shortie = new Shortie { Original = (string)json["short"]["original"], Short = (string)json["short"]["short"], Error = new ShortieException { Code = (int)json["short"]["error"]["code"], ErrorMessage = (string)json["short"]["error"]["msg"] } }; (); // / (); // No action taken public class Shortie { public string Original { get; set; } public string Shortened { get; set; } public string Short { get; set; } public ShortieException Error { get; set; } } public class ShortieException { public int Code { get; set; } public string ErrorMessage { get; set; } }
6. Using the function SelectToken to generate JToken objects can simplify query statements
1、SelectToken
SelectToken is a method on JToken, which takes the string path as the child Token name and returns the child Token. If the token is not found at the path location, the SelectToken returns an empty reference.
The path consists of the attribute name and period-delimited array index, such as manufacturer [0]. name.
JObject jObj = (json); JToken name = ("Name"); (());
Results: Jack
2. Use LINQ to SelectToken
SelectToken supports JSONPath query.Click here to learn more about JSONPath.
Check the age of the last colleague
//Convert json to JObjectJObject jObj = (json); var age = ("Colleagues[1].Age"); (()); // manufacturer with the name 'Acme Co' JToken acme = ("$.Manufacturers[?(@.Name == 'Acme Co')]"); (acme); // { "Name": "Acme Co", Products: [{ "Name": "Anvil", "Price": 50 }] } // name of all products priced 50 and above IEnumerable pricyProducts = ("$..Products[?(@.Price >= 50)].Name"); foreach (JToken item in pricyProducts) { (item); } // Anvil // Elbow Grease
Results: 29
3. Use JSONPath to SelectToken
SelectToken can be used in conjunction with standard LINQ methods.
Use SelectToken to query the names of all colleagues
JObject jObj = (json); var names = ("Colleagues").Select(p => p["Name"]).ToList(); foreach (var name in names) (()); IList<string> storeNames = ("Stores").Select(s => (string)s).ToList(); // Lambton Quay // Willis Street IList<string> firstProductNames = o["Manufacturers"].Select(m => (string)("Products[1].Name")).ToList(); // null // Headlight Fluid decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)("Products[0].Price"));
Results: Tom Abel
7. If the Key in Json is changing but the structure remains unchanged, how to obtain the desired content?
For example:
{ "trends": { "2013-05-31 14:31": [ { "name": "I'm not someone's idol", "query": "I'm not someone's idol", "amount": "65172", "delta": "1596" }, { "name": "World Smoke-free Day", "query": "World Smoke-free Day", "amount": "33548", "delta": "1105" } ] }, "as_of": 1369981898 }
The "2013-05-31 14:31" is a changing key. How to obtain the information such as "name", "query", "amount", "delta"?
With Linq, it can be done very simply:
var jObj = (jsonString); var tends = from c in () select (()); public class Trend { public string Name { get; set; } public string Query { get; set; } public string Amount { get; set; } public string Delta { get; set; } }
8. Comprehensive examples
void Main() { string json = "{\"Name\" : \"Jack\", \"Age\" : 34, \"Colleagues\" : [{\"Name\" : \"Tom\" , \"Age\":44},{\"Name\" : \"Abel\",\"Age\":29}] }"; // Get the employee name JObject jObject = (json); var name = <string>("Name"); (name); // Get employee age JToken jToken = ("Age"); (()); // Get colleague information JToken jToken1 = jObject["Colleagues"]; (()); ("============================="); // Get all names of employees and colleagues var names = from staff in () select (string)staff["Name"]; // var names = ("Colleagues").Select(p => p["Name"]).ToList(); foreach (var item in names) { (item); } ("============================="); // Modify Jack's age jObject["Age"] = 99; (()); // Modify the age of colleague Tome jToken1[0]["Age"] = 45; (()); ("============================="); // Abel resigns jObject["Colleagues"][1].Remove(); (()); // Remove Jack's colleagues ("Colleagues"); (()); ("============================="); // Jack lacks department information jObject["Age"].(new JProperty("Department", "President's Office")); // A new employee Jerry JObject linda = new JObject(new JProperty("Name", "Linda"), new JProperty("Age", "23")); (new JProperty("Colleagues", new JArray() { linda })); (()); } // Define other methods and classes here
This is all about this article about C# using LINQ to JSON. I hope it will be helpful to everyone's learning and I hope everyone will support me more.