JSON detailed (GO)

Source: Internet
Author: User

Tags: start convert mes label keyword BIRT ESC on () bar

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

Back to the top of the two structures 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       }]
Get back to the top of the JSON string

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

Back to top in JS how to use JSON

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, person            : [//array structure JSON object, can be nested using                        {                            id:1,                            Name: "Zhang San"                        },                        {                            id:2,                            name: "John Doe"                        }                   ], object            : {//Object structure JSON object                id:1,                msg: " Object in the object "                }        };

1, reading data from JSON

function Readjson () {            alert (obj.1);//Report syntax error, can use alert (obj["1"]), it is best not to do the keyword            alert (obj.2)            ; alert (obj.person[0].name); or alert (obj.person[0]["name"])            alert (obj.object.msg);//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            obj.sex= "male"//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 () {            obj.count = 10;//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 (var. c in obj) {                Console.log (c + ":", Obj[c]);}        }

The program output results are:

Back to the top of the. 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

protected void Page_Load (object sender, EventArgs e) {using (L2sdbdatacontext db = new L2sdbdatacontext                ()) {list<student> studentlist = new list<student> (); var query = from S in db.                                Tstudents Select New {Studentid=s.studentid, Name=s.name, Hometown=s.hometown, Gender=s.gen                                Der, Brithday=s.birthday, Classid=s.classid, Weight=s.weight, Height=s.height, Desc=s.des                c}; 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": 5,//number    of 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:

protected void Page_Load (object sender, EventArgs e) {using (L2sdbdatacontext db = new L2sdbdatacontext ()) {//Fetch data from the database and put it in list list<student> studentlist = new List<student                > (); var query = from S in db. Tstudents Select New {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);                        }//Based on the list created, the JSON data of the desired format is created using LINQ to JSON Lbmsg.innertext = new Jobject ( New Jproperty ("Total", Studentlist.count), New Jproperty ("Rows", n                                        EW Jarray (//Using LINQ to JSON can generate JSON data objects directly in the SELECT statement without the need for additional conversion procedures                                                From P in studentlist select New Jobject ( New Jproperty ("StudentID", P.studentid), new Jproperty                                            ("name", 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.

protected void Page_Load (object sender, 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= ' + ' &GT;STUDENTID&LT;/TD&GT;&LT;TD w            Idth= ' >name</td><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"], Jobje            ct["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 of JSON            foreach (Student Student in studentlist)            {                message + = String.Format (TPL, student. StudentID, student. Name,student. Hometown);            }
Back to top of the summary

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.

JSON detailed (GO)

Related Article

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.

Tags Index: