asp.net JObject operations

 

1. What is Linq to JSON used for?

  Linq to JSON is used to manipulate JSON objects. It 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 Fetch and modify part of the data instead of deserializing the whole.

2. Create JSON arrays and objects

Before doing Linq to JSON, it is necessary to first understand the classes used to manipulate Linq to JSON.

class name illustrate
JObject
 for manipulating JSON objects
JArray
 Manipulating JSON arrays in terms
JValue
 represents the value in the array
JProperty
 Represents an attribute in an object, in the form of "key/value"
JToken
 Used to store the result of Linq to JSON query

 

 

 

 

 

 

 

 

1. Create a JSON object

 
            JObject staff = new JObject();
            staff.Add(new JProperty("Name", "Jack"));
            staff.Add(new JProperty("Age", 33));
            staff.Add(new JProperty("Department", "Personnel Department"));
            staff.Add(new JProperty("Leader", new JObject(new JProperty("Name", "Tom"), new JProperty("Age", 44), new JProperty("Department", "Personnel Department"))));
            Console.WriteLine(staff.ToString());
 

result:

In addition, you can also obtain JObject.JArray in the following ways.

method   illustrate
JObject.Parse(string json)
json A string containing a JSON object, returned as a JObject object
JObject.FromObject(object o)

o is the object to be converted and returns a JObject object

JObject.Load(JsonReader reader)
The reader contains the content of the JSON object and returns a JObject object

 

 

 

 

 

 

2. Create JSON array

 
            JArray arr = new JArray();
            arr.Add(new JValue(1));
            arr.Add(new JValue(2));
            arr.Add(new JValue(3));
            Console.WriteLine(arr.ToString());
 

result:

3. Use Linq to JSON

1. The query
first prepares a Json string, which is a Json containing basic employee information

string json = "{\"Name\" : \"Jack\", \"Age\" : 34, \"Colleagues\" : [{\"Name\" : \"Tom\" , \"Age\":44},{\"Name\" : \"Abel\",\"Age\":29}] }";

①Get the name of the employee

 
            //Convert json to JObject
            JObject jObj = JObject.Parse(json);
            //Access by property name or index, only its own property name, not all
            JToken ageToken =  jObj["Age"];
            Console.WriteLine(ageToken.ToString());
 

result:

②Get all the names of the employee's colleagues

 
            //Convert json to JObject
            JObject jObj = JObject.Parse(json);
            var names=from staff in jObj["Colleagues"].Children()
                             select (string)staff["Name"];
            foreach (var name in names)
                Console.WriteLine(name);
 

"Children()" can return all objects in the array

result:

2. Modify

① Now we find that Jack's age in the obtained json string should be 35

            //Convert json to JObject
            JObject jObj = JObject.Parse(json);
            jObj["Age"] = 35;
            Console.WriteLine(jObj.ToString());

result:

Be careful not to modify it by:

            JObject jObj = JObject.Parse(json);
            JToken age = jObj["Age"];
            age = 35;

②Now we find that Jack's colleague Tom's age is wrong, it should be 45

 
            //Convert json to JObject
            JObject jObj = JObject.Parse(json);
            JToken colleagues = jObj["Colleagues"];
            colleagues[0]["Age"] = 45;
            jObj["Colleagues"] = colleagues;//After modification, assign it to the object
            Console.WriteLine(jObj.ToString());
 

result:

3. Delete
① Now we want to delete Jack's colleague

            JObject jObj = JObject.Parse(json);
            jObj.Remove("Colleagues");//Follows the property name
            Console.WriteLine(jObj.ToString());

result:

②Now we find out that Abel is not Jack's colleague and ask to be removed from it

            JObject jObj = JObject.Parse(json);
            jObj["Colleagues"][1].Remove();
            Console.WriteLine(jObj.ToString());

result:

4. Add
① We found that the department information was missing from Jack's information, and we were required to add it after Age

            //Convert json to JObject
            JObject jObj = JObject.Parse(json);
            jObj["Age"].Parent.AddAfterSelf(new JProperty("Department", "Personnel Department"));
            Console.WriteLine(jObj.ToString());

result:

②Now we find out that Jack's company has a new colleague Linda

 
            //Convert json to JObject
            JObject jObj = JObject.Parse(json);
            JObject linda = new JObject(new JProperty("Name", "Linda"), new JProperty("Age", "23"));
            jObj["Colleagues"].Last.AddAfterSelf(linda);
            Console.WriteLine(jObj.ToString());
 

result:

4. Simplify the query statement

Using the function SelectToken can simplify the query statement, specifically:
①Use SelectToken to query the name

            JObject jObj = JObject.Parse(json);
            JToken name = jObj.SelectToken("Name");
            Console.WriteLine(name.ToString());

result:

②Use SelectToken to query the names of all colleagues

            JObject jObj = JObject.Parse(json);
            var names = jObj.SelectToken("Colleagues").Select(p => p["Name"]).ToList();
            foreach (var name in names)
                Console.WriteLine(name.ToString());

result:

③ Query the age of the last colleague

            //Convert json to JObject
            JObject jObj = JObject.Parse(json);
            var age = jObj.SelectToken("Colleagues[1].Age");
            Console.WriteLine(age.ToString());

result:

 

FAQ

1. If the Key in Json changes but the structure remains the same, how to get the desired content?

E.g:
 
1 {
 2 "trends":
 3 {
 4 "2013-05-31 14:31":
 5 [
 6 {"name":"I'm not someone's idol",
 7 "query":"I'm not someone's idol",
 8 "amount":"65172",
 9 "delta":"1596"},
10 {"name":"World No Tobacco Day","query":"World No Tobacco Day","amount":"33548","delta":"1105"},
11 {"name":"The cutest height difference","query":"The cutest height difference","amount":"32089","delta":"1069"},
12 {"name":"China Partner","query":"China Partner","amount":"25634","delta":"2"},
13 {"name":"exo回归","query":"exo回归","amount":"23275","delta":"321"},
14 {"name":"New Kiss","query":"New Kiss","amount":"21506","delta":"283"},
15 {"name":"Attack on Titan","query":"Attack on Titan","amount":"20358","delta":"46"},
16 {"name":"Whose youth is not missing","query":"Whose youth is not missing","amount":"17441","delta":"581"},
17 {"name":"I love Lucky Seven","query":"I love Lucky Seven","amount":"15051","delta":"255"},
18 {"name":"母爱10平方","query":"母爱10平方","amount":"14027","delta":"453"}
19 ]
20 },
21 "as_of":1369981898
22 }
 

Among them, "2013-05-31 14:31" is the changed key. How to get the "name", "query", "amount", "delta" and other information?
It can be easily done through Linq:

 
var jObj = JObject.Parse(jsonString);
            var tends = from c in jObj.First.First.First.First.Children()
                        select JsonConvert.DeserializeObject<Trend>(c.ToString());
public class Trend
{
            public string Name { get; set; }
            public string Query { get; set; }
            public string Amount { get; set; }
            public string Delta { get; set; }
}
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324913813&siteId=291194637