Question: JsonConvert; results: JSON in detail

Source: Internet
Author: User
Tags string back

JSON detailed

The full name of JSON is "JavaScript Object Notation", which means the JavaScript objects notation, which is a text-based, language-independent, lightweight data interchange format. XML is also a data interchange format, why not choose XML? Since XML can be used as a cross-platform data interchange format, it is very inconvenient to process XML in JS (abbreviated JavaScript), while XML tags are much more than data, which increases the traffic generated by the interchange, and JSON does not have any tags attached to it, which can be treated as objects in JS. So we are more inclined to choose JSON to exchange data. This article explains JSON mainly from the following aspects.

Two kinds of structure of 1,json
2, recognize the JSON string
3, how to use JSON in JS
4, in. How to use JSON in net
5, summary

Two kinds of structure of JSON

JSON has two representations of structures, objects, and arrays.
The object structure starts with "{" Curly braces and ends with "}" curly braces. The middle section consists of 0 or more "key (key)" pairs consisting of "," separated by "/value", the keywords and values separated by ":", and the grammatical structure such as code.

{    key1:value1,    key2:value2,    ...}

Where the keyword is a string, and the value can be a string, a value, a true,false,null, an object, or an array

The array structure ends with "[" Start, "]". The middle consists of 0 or more lists of values separated by ",", grammatical structures such as code.

[    {        key1:value1,        key2:value2     },    {         key3:value3,         key4:value4       }]
Recognize JSON strings

I've been confused before, and I can't tell the difference between a normal string, a JSON string, and a JSON object. After some research, I finally figured it out. For example, in JS.

String: This is a good explanation for the use of "" "double quotation marks or single quotation marks to include characters. For example: var comstr = ' This is string ';
JSON string: Refers to a JS string that conforms to the JSON format requirements. For example: var jsonstr = "{studentid: '", Name: ' Tmac ', Hometown: ' USA '} ";
JSON object: Refers to a JS object that conforms to the JSON format requirements. For example: var jsonobj = {studentid: "", "Name:" Tmac ", Hometown:" USA "};

How to use JSON in JS

JSON is a subset of JS, so it is easy to read and write JSON in JS. There are two ways to read and write JSON, respectively, using "." operator and the "[Key]" method.
We first define a JSON object, the code is as follows.

var obj = {            1: "Value1",            "2": "value2",            count:3,            // array structure JSON object, can be nested using { Id:1, Name: "Zhang San" }, {id:2, Name: "John Doe"// Object Structure JSON object Id:1, msg: "Object in Object" }}; 

1, reading data from JSON

function Readjson () {            // will report syntax error, can be used alert (obj["1"]); it's best not to do the keyword            // Ibid //// or alert (obj.object["MSG"])}       

2. Write data to JSON

For example, to add a piece of data to the JSON, the code is as follows:

function Add () {             // adds a record to the JSON object            // or obj["sex"]= "Male"}    

JSON object after adding data

3. Modify the data in the JSON

We are now going to modify the value of count in JSON as follows:

function Update () {            // or obj["Count"]=10        }  

The modified JSON.

4. Delete data from JSON

We now implement the deletion of the count from JSON data, the code is as follows:

function Delete () {            Delete obj.count;        }  

Post-Deletion JSON

You can see that count has been removed from the JSON object.

5, traversing the JSON object

You can use for...in ... Loop to iterate through the data in the JSON object, for example, we want to traverse the value of the output obj object, the code is as follows:

function Traversal () {            for ( in obj) {Console.log (c + ":", Obj[c]);}}    

The program output results are:

How to use JSON in. Net

When it comes to using JSON in. NET, you have to mention Json.NET, which is a very well-known tool for working with JSON in. NET, the following two features are most commonly used.

1. Convert. NET objects to JSON strings by serialization

In the Web development process, we often need to convert the data from the database (typically a collection, a list or an array, etc.) to a JSON format string back to the client, which needs to be serialized, here is the SerializeObject method of the JsonConvert object. Its syntax is Jsonconvert.serializeobject (object), and "Object" in the code is the. NET object to serialize, and the JSON string is returned after serialization.

For example, now we have a tstudent student table, the fields in the table and the existing data

From the table we can see a total of five data, now we want to extract the data from the database, and then use the Json.NET JsonConvert object to serialize them as a JSON string, and displayed on the page. C # code is as follows

Protectedvoid Page_Load (Objectsender, EventArgs e) {using (L2sdbdatacontext db =NewL2sdbdatacontext ()) {list<student> studentlist =New list<student>();var query =from SInchDb. TstudentsSelectNew{studentid=S.studentid, Name=S.name, hometown=s.hometown, Gender=s.gender, Brithday=s.birthday, Classid=s.classid, Weight=s.weight, Height=s.height, Desc=s.desc}; foreach (var item in Query) {Student Student = new Student {studentid=item. Studentid,name=item. Name,hometown=item. Hometown,gender=item. Gender,brithday=item. Brithday,classid=item. Classid,weight=item. Weight,height=item. Height,desc=item. DESC}; Studentlist.add (student); } lbmsg.innertext = Jsonconvert.serializeobject (studentlist);}}    

Output results

We can see that the 5 records in the database are all taken out and converted into JSON strings.

2. Customizing JSON Data Using LINQ to JSON

Using the JsonConvert object's serializeobject simply converts a list or collection to a JSON string. However, sometimes our front-end framework such as EXTJS for the data format returned by the server has certain requirements, such as the following data format, then need to use Json.NET LINQ to Json,linq to JSON function is to customize the JSON data according to the format required.

For example, the JSON format, often used in pagination, is as code:

{     // Total Records    "Rows": [        //data list in JSON format ]}     

Before using LINQ to Json, you need to reference the Newtonsoft.json DLL and the namespace of the using Newtonsoft.Json.Linq. LINQ to JSON mainly uses four objects, Jobject, Jarray, Jproperty, and Jvalue, Jobject is used to generate a JSON object, simply to generate "{}", Jarray to generate a JSON array, that is, "[] ", Jproperty is used to generate a JSON data in the form of a key/value value, while Jvalue generates a JSON value directly. Here we will return the data in the page format using LINQ to JSON. The code is as follows:

Protectedvoid Page_Load (Objectsender, EventArgs e) {using (L2sdbdatacontext db =NewL2sdbdatacontext ()) {//Fetch data from the database and put it in list list<student> studentlist =New list<student>();var query =from SInchDb. TstudentsSelectNew{StudentID =S.studentid, Name =S.name, hometown =S.hometown, Gender =S.gender, Brithday =S.birthday, ClassID =S.classid, Weight =S.weight, Height =S.height, Desc =S.DESC};foreach (VAR itemInchQuery) {Student Student =New Student {StudentID = Item. StudentID, Name = Item. Name, Hometown = Item. Hometown, Gender = Item. Gender, Brithday = Item. Brithday, ClassID = Item. ClassID, Weight = Item. Weight, Height = Item. Height, Desc =Item. DESC}; Studentlist.add (student); }//Creates JSON data in the desired format using LINQ to JSON based on the list created Lbmsg.innertext =NewJobject (New Jproperty ("Total", Studentlist.count),New Jproperty ("Rows",NewJarray (//Using LINQ to JSON, you can generate JSON data objects directly in the SELECT statement without the need for additional conversion procedures from p in studentlist Span style= "color: #0000ff;" >select new Jobject ( "studentid  ",p.studentid", new Jproperty ( "name" Span style= "color: #000000;" >,p.name), new jproperty ( " hometown,p.hometown ) ) ) ) ). ToString (); } } 

The output is:

3, processing the JSON data submitted by the client

The data submitted by the client is typically a JSON string with a better operation (object-oriented approach), so we will generally try to convert the JSON string to a JSON object. For example, the client submits the following array format JSON string.

[    {studentid: "+", Name: "AAA", Hometown: "China"},    {studentid: "101", Name: "BBB", Hometown: "Us"},    {studentid: "102", Name: "CCC", Hometown: "England"}]  

On the server side, you can easily convert a JSON string to a JSON object using the parse method of Jobject or Jarray, and then extract the data by object. The following is the service-side code.

Protectedvoid Page_Load (Objectsender, EventArgs e) {String inputjsonstring =@"[{studentid: ' + ', Name: ' AAA ', Hometown: ' China '}, {studentid: ' 101 ', Name: ' BBB ', Hometown: ' Us '}, {studentid: ' 102 ', Name: ' CCC ', Hometown: ' England '}]"; Jarray jsonobj =Jarray.parse (inputjsonstring);String message =@"<table border= ' 1 ' > <tr><td width= ' ">studentid</td><td width= ' >Name</td> &LT;TD width= ' >Hometown</td></tr>";String TPL ="<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>"; foreach (jobject jobject  in jsonobj) {message + = String.Format (TPL, jobject["studentid"], jobject["Name"],jobject["hometown"]);} Message + = "</table>"; lbmsg.innerhtml = message;}               

Output Result:

of course, the service side can use the JsonConvert Deserializeobject method in addition to using LINQ to JSON for converting JSON strings. The following code implements the same functionality as above.

list<student> studentlist = jsonconvert.deserializeobject<list<student>> (inputJsonString); // Note that this must be a list<student> type because the client is submitting an array json in             studentlist)            {                message + =  String.Format (TPL, student. StudentID, student. Name,student. Hometown); }
Summarize

On the client side, the read-write JSON object can use the "." operator or "[" Key "]", the JSON string is converted to a JSON object using the eval () function.
On the server side, the JSON string converted by the. NET object takes precedence using the SerializeObject method of the JsonConvert object, customizing the output JSON string using LINQ to JSON. Converting from a JSON string to a. NET object takes precedence over the Deserializeobject method of the JsonConvert object, and then also uses LINQ to JSON.

Problem: JsonConvert; Results: JSON detailed

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.