Interview question: What is JSON? __json

Source: Internet
Author: User
Tags serialization string back
JSON detailed

The full name of JSON is "JavaScript Object notation", which means JavaScript representation, a lightweight data interchange format that is text-based and language-independent. XML is also a data interchange format, so why not choose XML? Because XML can be used as a Cross-platform data interchange format, it is inconvenient to process XML in JS (JavaScript shorthand), while XML tags are more than data, which increases the traffic generated by the exchange, and JSON does not have any additional tags, which can be treated as objects in JS. So we're more inclined to choose JSON to exchange data. This article mainly describes JSON 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, summarizing the two structures of JSON

JSON has two representations of structures, objects, and arrays.
The object structure begins with the "{" Brace and ends with the curly braces "}". The middle section consists of 0 or more "key"/value (value) pairs, separated by ":" Between the keyword and the value, and the syntax structure is like code.

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

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

The array structure begins with "[", "]" ends. The middle consists of 0 or more list of values separated by "," and the syntax structure is like code.

[
    {
        key1:value1,
        key2:value2 
    },
    {
         key3:value3,
         key4:value4   
    }
]
Understanding JSON Strings

I've always had a confusion about the difference between a normal string, a JSON string, and a JSON object. After some research finally to understand. For example, in JS.

String: This is a good explanation of the characters that are included with "double quotes or" single quotes. For example: var comstr = ' This is string ';
JSON string: Refers to a JS string that conforms to the JSON format requirement. For example: var jsonstr = "{studentid: ' m ', Name: ' Tmac ', Hometown: ' USA '}";
JSON object: A JS object that conforms to the JSON format requirements. For example: var jsonobj = {studentid: "M", Name: "Tmac", Hometown: "USA"}; How to use JSON in JS

JSON is a subset of JS, so you can easily read and write json in JS. There are two ways to read and write JSON, respectively, by using the "." The operator and the "[Key]" method.
Let's start by defining a JSON object with the following code.

var obj = {
            1: "Value1",
            "2": "value2",
            count:3, person
            : [//array structure JSON object, can be nested using
                        {
                            id:1,
                            Name: "John"
                        },
                        {
                            id:2,
                            name: "Dick"
                        }
                   ], object
            : {//Objects structure JSON object
                id:1,
                msg: " Object in the object '    
            }
        };

1, reading data from JSON

function Readjson () {
            alert (obj.1);//will report syntax errors, you can use alert (obj["1"]); it is best not to do keyword
            alert (obj.2);/Ibid.

            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 JSON, the code reads as follows:

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

The JSON object after adding the data is shown in figure:

3, modify the data in the JSON

We're now going to change the value of count in JSON with the following code:

function Update () {
            obj.count = 10;//or obj[' count ']=10
        }

The modified JSON is shown in figure.

4, delete the data in JSON

We now implement the data to delete count from JSON, as follows:

function Delete () {
            delete obj.count;
        }

After the deleted JSON as shown

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

5, traversing the JSON object

You can use for...in ... Loop to traverse the data in the JSON object, such as the value of the output obj object that we want to traverse, the code reads as follows:

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

The result of the program output is:

How to use JSON in. NET

When it comes to using JSON in. NET, you have to mention Json.NET, a very famous tool for processing JSON in. NET, the following two features are most commonly used.

1, converting a. NET object to a JSON string by serialization

In web development, we often need to convert data that is queried from the database (typically a collection, list, or array) to the JSON format string back to the client, which requires serialization, where the JsonConvert object's SerializeObject method is used. The syntax format 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 with fields in the table and existing data as shown in the figure

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

protected void Page_Load (object sender, EventArgs e) {using (L2sdbdatacontext db = new L2sdbdataconte
                XT ()) {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);
            } Lbmsg.innertext = Jsonconvert.serializeobject (studentlist); }
        }

Output results

As we can see from the diagram, the 5 records in the database are all taken out and converted to JSON strings.

2, customizing JSON Data with 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 to the server to return the data format is a certain requirement, such as the following data format, then need to use the Json.NET LINQ to Json,linq to JSON's role is to customize the JSON data according to the required format.

such as the JSON format often used in pagination, such as code:

{ 
    "total": 5,//number
    of records "Rows": [
        List of data in//json format
    ]
}

Before using LINQ to Json, you need to refer to the Newtonsoft.json DLL and the using Newtonsoft.Json.Linq namespace. LINQ to JSON primarily uses the four objects jobject, Jarray, Jproperty, and Jvalue, jobject to generate a JSON object, simply to generate "{}", which is used to generate a JSON array, which is "[] , Jproperty is used to generate a JSON data formatted as a Key/value value, while Jvalue generates a JSON value directly. Here we'll use LINQ to JSON to return the data in the paging format above. The code is as follows:

protected void Page_Load (object sender, EventArgs e) {using (L2sdbdatacontext db = new L2sdbdataconte XT ()) {//Remove the data from the database and put it in the list list<student> studentlist = new List<st
                Udent> (); 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 created list use LINQ to JSON to create the desired format JSON data Lbmsg.innertext = new Jobject (
                                New Jproperty ("Total", Studentlist.count), New Jproperty ("Rows",
                                        New Jarray (////Using LINQ to JSON can generate JSON data objects directly in a SELECT statement without any other conversion process
                                                From P in studentlist select New Jobject (
                                                 New Jproperty ("StudentID", P.studentid),
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.

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.