Json.NET Series Tutorial--linq to JSON "likes"

Source: Internet
Author: User

what is Linq to JSON for?

LINQ to JSON is used to manipulate JSON objects. You can use it to quickly query, modify, and create JSON objects. When the JSON object content is complex and we only need a small subset of the data, consider using LINQ to JSON to read and modify portions of the data instead of deserializing all.

two. Creating JSON arrays and objects

Before you make LINQ to JSON, let's first look at the classes used to manipulate LINQ to JSON.

Class name Description
Jobject
For manipulating JSON objects
Jarray
Language manipulation JSON array
Jvalue
Represents a value in an array
Jproperty
Represents an attribute in an object, in the form of "Key/value"
Jtoken
Results for storing LINQ to JSON queries

1. Creating a JSON Object

            Jobject staff = new Jobject ();            Staff. ADD (New Jproperty ("Name", "Jack"));            Staff. ADD (New Jproperty ("Age",));            Staff. ADD (New Jproperty ("Department", "Personnel Department"));            Staff. ADD (New Jproperty ("Leader", New Jobject ("Name", "Tom"), New Jproperty ("Age", "a"), New Jproperty (" Department "," Personnel Department ")));            Console.WriteLine (staff. ToString ());

Results:

In addition to this, it is possible to get jobject.jarray similar by the way.

Method Description
Jobject.parse (String json)
JSON string containing JSON object, returned as Jobject object
Jobject.fromobject (Object o)

o Returns an Jobject object for the object to be converted

Jobject.load (Jsonreader Reader)
Reader contains the contents of the JSON object, returning a Jobject object

2. Creating 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 ());

Results:

three. Using LINQ to JSON

1. Enquiry
Prepare the JSON string First, which is a JSON containing basic employee information

String json = "{\" name\ ": \" Jack\ ", \" age\ ":" Colleagues\ ": [{\" name\ ": \" tom\ ", \" age\ ": 44},{\" name\ ": \" abel\ ", \" age\ ": 29}]}";

① get the name of the employee

            Convert JSON to Jobject            jobject jobj = Jobject.parse (JSON);            accessed by a property name or index, only its own property name, not all            jtoken agetoken =  jobj["age"];            Console.WriteLine (Agetoken.tostring ());

Results:

② 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 objects in all arrays

Results:

2. Modifications

① now we find that Jack's age should be 35 in the JSON string obtained

            Convert JSON to Jobject            jobject jobj = Jobject.parse (JSON);            Jobj["Age" = +;            Console.WriteLine (Jobj.tostring ());

Results:

Be careful not to 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 and should be 45.

            Convert JSON to Jobject            jobject jobj = Jobject.parse (JSON);            Jtoken colleagues = jobj["colleagues"];            Colleagues[0]["age"] =;            Jobj["colleagues"] = colleagues;//modified, then assigned to the Object            Console.WriteLine (jobj.tostring ());

Results:

3. Delete

① now we want to remove Jack's colleague.

            Jobject jobj = Jobject.parse (JSON);            Jobj.remove ("colleagues");//followed by the attribute name            Console.WriteLine (jobj.tostring ());

Results:

② now we find out that Abel is not Jack's colleague, asking to be removed from

            Jobject jobj = Jobject.parse (JSON);            Jobj["colleagues"][1]. Remove ();            Console.WriteLine (Jobj.tostring ());

Results:

4. Add
① we found that Jack's information was missing from the department, and that we had to add it back to age.

            Convert JSON to Jobject            jobject jobj = Jobject.parse (JSON);            Jobj["Age"]. Parent.addafterself (New Jproperty ("Department", "Personnel Department"));            Console.WriteLine (Jobj.tostring ());

Results:

② now we find out that Jack's got a new colleague, Linda.

            Convert JSON to Jobject            jobject jobj = Jobject.parse (JSON);            Jobject linda = new Jobject (New Jproperty ("Name", "Linda"), New Jproperty ("Age", "all");            Jobj["colleagues"]. Last.addafterself (Linda);            Console.WriteLine (Jobj.tostring ());

Results:

Four. Simplifying query Statements

Using the function Selecttoken can simplify the query statement, specifically:
① using Selecttoken to query names

            Jobject jobj = Jobject.parse (JSON);            Jtoken name = Jobj.selecttoken ("name");            Console.WriteLine (name. ToString ());

Results:

② uses Selecttoken to find out the names of all his 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 ());

Results:

③ 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 ());

Results:

FAQs

1. If the key in JSON is changed but the structure is not changed, how do you get what you want?

For example:
1 {2 "Trends": 3 {4 "2013-05-31 14:31": 5 [6 {"Name": "I am not an idol", 7 "query": "I am not an idol", 8 "Amount": "65172", 9 "Delta": "159 6 "},10 {" "Name": "World No Tobacco Day", "Query": "World No 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 ":" China partner "," Query ":" China partner "," Amount ":" 25634 "," Delta ":" 2 "},13 {" name ":" Exo return "," Query ":" Exo regression "," Amount ":" 23275 "," Delta ":" 321 "},14 {" name ":" New Kiss, "" Query ":" New Kiss, "" Amount ":" 21506 "," Delta ":" 283 "},15 {" name ":" Attacking Titan "," Query ":" Attacking Titan "," Amount ":" 20358 "," Delta ":"},16 "," name ":" Who's 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": "Motherly 10 Square", "Query": "Motherly love 10 square", "Amount": "14027", "Delta": "453"}19]20},21 "as_of": 136998189822}

One of the "2013-05-31 14:31" is the change of key, how to get the "name", "Query", "Amount", "Delta" and other information?
LINQ makes it easy to:

var jobj = Jobject.parse (jsonstring);            var tends = from C in JObj.First.First.First.First.Children ()                        Select Jsonconvert.deserializeobject<trend> (c . ToString ());p Ublic class trend{public            string Name {get; set;}            public string Query {get; set;}            public string Amount {get; set;}            public string Delta {get; set;}}

"Reprint" http://www.cnblogs.com/usharei/archive/2012/04/24/2467578.html

Json.NET Series Tutorial--linq to JSON "likes"

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.