Json to JObject conversion method, jsontojobject Conversion

Source: Internet
Author: User

Json to JObject conversion method, jsontojobject Conversion

Linq to JSON is used to operate JSON objects. it can be used to quickly query, modify, and create JSON objects. when the content of a JSON object 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 all.

2. Create a JSON array and Object

Before you perform the Linq to JSON operation, you must first understand the classes used to operate the Linq to JSON.

Class Name Description
JObject
JSON object operation
JArray
Operation JSON Array
JValue
Indicates the value in the array.
JProperty
Attribute in the object, in the form of "key/value"
JToken
It is used to store the results of the query by the Linq to JSON.

 

 

 

 

 

 

 

 

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 obtain JObject. JArray in the following way.

Method Description
JObject.Parse(string json)
Json string containing a JSON object, which is returned as a JObject object
JObject.FromObject(object o)

O is the object to be converted, and a JObject object is returned.

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

 

 

 

 

 

 

2. Create a 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. Query
First, prepare a Json string. It is a Json string containing basic employee information.

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

① Obtain the employee's name

// Convert json to JObject jObj = JObject. parse (json); // access by attribute name or index. It is only your own attribute name, not all JToken ageToken = jObj ["Age"]; Console. writeLine (ageToken. toString ());

Result:

② Obtain all the names of the employee's colleagues

// Convert json to 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 ()" returns objects in all arrays.

Result:

2. Modify

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

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

Result:

Do not modify it in the following ways:

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

② Now we find Jack's colleague Tom's age is wrong. It should be 45.

// Convert json to 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 colleagues

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

Result:

② Now we find that Abel is not a colleague of Jack and asks to delete it.

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

Result:

4. Add
① We found that Jack's information contained less Department Information and required that we add it to the end of Age.

// Convert json to JObject jObj = JObject. parse (json); jObj ["Age"]. parent. addAfterSelf (new JProperty ("Department", "Personnel Department"); Console. writeLine (jObj. toString ());

Result:

② Now we find that Jack has a new colleague, Linda.

// Convert json to 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. Simplified query statements

The SelectToken function simplifies the query statement:
① 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 jObj = JObject. parse (json); var age = jObj. selectToken ("Colleagues [1]. age "); Console. writeLine (age. toString ());

Result:

 

FAQ

1. If the Key in Json is changed but the structure remains unchanged, how can I get the desired content?

For example:
1 {2 "trends": 3 {4 "2013-05-31": 5 [6 {"name": "Who am not my idol", 7 "query ": "My idol is not", 8 "amount": "65172", 9 "delta": "1596" },10 {"name": "World Tobacco Day ", "query": "World Tobacco Day", "amount": "33548", "delta": "1105" },11 {"name": "The most cute height difference ", "query": "The most cute height difference", "amount": "32089", "delta": "1069" },12 {"name": "Chinese partners ", "query": "Chinese partners", "amount": "25634", "delta": "2" },13 {"name": "exo regression ", "query": "exo regression", "amount": "23275", "delta": "321" },14 {"name": "New kiss ", "query": "A New kiss", "amount": "21506", "delta": "283" },15 {"name": "Attacking giant ", "query": "Attacking giants", "amount": "20358", "delta": "46" },16 {"name ": "Who is not missing?", "query": "Who 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 square meters of maternal care", "query": "10 square meters of maternal care", "amount": "14027", "delta ": "453"} 19] 20}, 21 "as_of": 136998189822}

"" Is the changed key. How can I obtain information such as "name", "query", "amount", and "delta?
Using Linq, you can easily:

 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; }}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.