Home > Web Front-end > JS Tutorial > An article to let you know in detail what JSON is

An article to let you know in detail what JSON is

王林
Release: 2019-08-28 15:09:48
forward
2839 people have browsed it

JSON detailed explanation:

The full name of JSON is "JavaScript Object Notation", which means JavaScript object notation. It is a text-based, language-independent, lightweight data exchange format. XML is also a data exchange format. Why wasn't XML chosen? Although XML can be used as a cross-platform data exchange format, it is very inconvenient to process XML in JS (abbreviation for JavaScript). At the same time, there are more XML tags than data, which increases the traffic generated by the exchange, while JSON does not have any tags attached. JS can be processed as objects, so we prefer JSON to exchange data. This article mainly explains JSON from the following aspects.

1, Two structures of JSON
2, Understanding JSON strings
3, How to use JSON in JS
4, How to use JSON in .NET
5, Summary

1. Two structures of JSON

JSON has two representation structures, objects and arrays.
The object structure starts with "{" braces and ends with "}" braces. The middle part consists of 0 or more "key (keyword)/value (value)" pairs separated by ",". Keywords and values ​​are separated by ":", and the syntax structure is like code.

{
    key1:value1,
    key2:value2,
    ...
}
Copy after login

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

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

[
    {
        key1:value1,
        key2:value2 
    },
    {
         key3:value3,
         key4:value4   
    }
]
Copy after login

2. Understanding JSON strings

#I have always been confused before, and I can’t distinguish between ordinary strings and json characters The difference between string and json object. After some research I finally figured it out. For example, in js.

String: This is easy to explain. It refers to characters enclosed by "" double quotes or '' single quotes. For example: var comStr = 'this is string';
json string: refers to a js string that meets the json format requirements. For example: var jsonStr = "{StudentID:'100',Name:'tmac',Hometown:'usa'}";
json object: refers to a js object that meets the json format requirements. For example: var jsonObj = { StudentID: "100", Name: "tmac", Hometown: "usa" };

3. 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 methods for reading and writing JSON, namely using the "." 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: [ //数组结构JSON对象,可以嵌套使用
                        {
                            id: 1,
                            name: "张三"
                        },
                        {
                            id: 2,
                            name: "李四"
                        }
                   ],
            object: { //对象结构JSON对象
                id: 1,
                msg: "对象里的对象"    
            }
        };
Copy after login

1. Read data from JSON

function ReadJSON() {
            alert(obj.1); //会报语法错误,可以用alert(obj["1"]);说明数字最好不要做关键字
            alert(obj.2); //同上

            alert(obj.person[0].name); //或者alert(obj.person[0]["name"])
            alert(obj.object.msg); //或者alert(obj.object["msg"])
        }
Copy after login

2. Write data to JSON

For example, if you want to add a piece of data to JSON, the code As shown below:

function Add() { 
            //往JSON对象中增加了一条记录
            obj.sex= "男" //或者obj["sex"]="男"
        }
Copy after login

The JSON object after adding data is as follows:

An article to let you know in detail what JSON is

3. Modify the data in JSON

We Now we need to modify the value of count in JSON. The code is as follows:

function Update() {
           obj.count = 10; //或obj["count"]=10
       }
Copy after login

The modified JSON is as shown in the figure:

An article to let you know in detail what JSON is

4. Delete the Data

We now delete the count data from JSON. The code is as follows:

function Delete() {            
    delete obj.count;//或obj["count"]
}
Copy after login

The deleted JSON is as shown in the figure:

An article to let you know in detail what JSON is

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

5. Convenience JSON object

You can use the for...in...loop to traverse the data in the JSON object. For example, if 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]);
            }
}
Copy after login

The program output result is:

An article to let you know in detail what JSON is

##4. How to use JSON# in .NET ##When it comes to using JSON in .net, we have to mention JSON.NET. It is a very famous tool for processing JSON in .net. The following two functions are most commonly used.

1. Convert .NET objects into JSON strings through serialization

In the web development process, we often need to query data from the database (usually a set, list or array, etc.) into a JSON format string and send it back to the client, which requires serialization. The

SerializeObject

method of the JsonConvert object is used here. The syntax format is:

JsonConvert

.SerializeObject(object)The "object" in the code is the sequence .NET object, the json string returned after serialization.

For example, now we have a TStudent student table. The fields and existing data in the table are as shown in the figure

An article to let you know in detail what JSON is

从表中我们可以看到一共有五条数据,现在我们要从数据库中取出这些数据,然后利用JSON.NET的JsonConvert对象序列化它们为json字符串,并显示在页面上。C#代码如下

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.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);
            }
        }
Copy after login

输出结果为:

An article to let you know in detail what JSON is

从图中我们可以看到,数据库中的5条记录全部取出来并转化为json字符串了。

2,使用LINQ to JSON定制JSON数据

使用JsonConvert对象的SerializeObject只是简单地将一个list或集合转换为json字符串。但是,有的时候我们的前端框架比如ExtJs对服务端返回的数据格式是有一定要求的,比如下面的数据格式,这时就需要用到JSON.NETLINQ to JSON,LINQ to JSON的作用就是根据需要的格式来定制json数据。

比如经常用在分页的json格式如代码:

{ 
    "total": 5, //记录总数
    "rows":[
        //json格式的数据列表
    ]
}
Copy after login

使用LINQ to JSON前,需要引用Newtonsoft.Jsondllusing Newtonsoft.Json.Linq的命名空间。LINQ to JSON主要使用到JObject, JArray, JProperty和JValue这四个对象,JObject用来生成一个JSON对象,简单来说就是生成”{}”,JArray用来生成一个JSON数组,也就是”[]”,JProperty用来生成一个JSON数据,格式为key/value的值,而JValue则直接生成一个JSON值。下面我们就用LINQ to JSON返回上面分页格式的数据。代码如下:

protected void Page_Load(object sender, EventArgs e)
        {
            using (L2SDBDataContext db = new L2SDBDataContext())
            {
                //从数据库中取出数据并放到列表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);
                }

                //基于创建的list使用LINQ to JSON创建期望格式的JSON数据
                lbMsg.InnerText = new JObject(
                        new JProperty("total",studentList.Count),
                        new JProperty("rows",
                                new JArray(
                                        //使用LINQ to JSON可直接在select语句中生成JSON数据对象,无须其它转换过程
                                        from p in studentList
                                        select new JObject(
                                                new JProperty("studentID",p.StudentID),
                                                new JProperty("name",p.Name),
                                                new JProperty("homeTown",p.Hometown)
                                            )
                                    )
                            )
                    ).ToString();
            }
        }
Copy after login

输出结果为:

An article to let you know in detail what JSON is

3、处理客户端提交的客户端数据

客户端提交过来的数据一般都是json字符串,有了更好地进行操作(面向对象的方式),所以我们一般都会想办法将json字符串转换为json对象。例如客户端提交了以下数组格式json字符串。

[
    {StudentID:"100",Name:"aaa",Hometown:"china"},
    {StudentID:"101",Name:"bbb",Hometown:"us"},
    {StudentID:"102",Name:"ccc",Hometown:"england"}
]
Copy after login

在服务端就可以使用JObject或JArray的Parse方法轻松地将json字符串转换为json对象,然后通过对象的方式提取数据。下面是服务端代码。

protected void Page_Load(object sender, EventArgs e)
        {
            string inputJsonString = @"
                [
                    {StudentID:&#39;100&#39;,Name:&#39;aaa&#39;,Hometown:&#39;china&#39;},
                    {StudentID:&#39;101&#39;,Name:&#39;bbb&#39;,Hometown:&#39;us&#39;},
                    {StudentID:&#39;102&#39;,Name:&#39;ccc&#39;,Hometown:&#39;england&#39;}
                ]";
            JArray jsonObj = JArray.Parse(inputJsonString);
            string message = @"<table border=&#39;1&#39;>
                    <tr><td width=&#39;80&#39;>StudentID</td><td width=&#39;100&#39;>Name</td><td width=&#39;100&#39;>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;
        }
Copy after login

输出结果为:

An article to let you know in detail what JSON is

当然,服务端除了使用LINQ to JSON来转换json字符串外,也可以使用JsonConvertDeserializeObject方法。如下面代码实现上面同样的功能。

List<Student> studentList = JsonConvert.DeserializeObject<List<Student>>(inputJsonString);//注意这里必须为List<Student>类型,因为客户端提交的是一个数组json
            foreach (Student student in studentList)
            {
                message += String.Format(tpl, student.StudentID, student.Name,student.Hometown);
            }
Copy after login

总结:

在客户端,读写json对象可以使用”.”操作符或”["key”]”,json字符串转换为json对象使用eval()函数。
在服务端,由.net对象转换json字符串优先使用JsonConvert对象的SerializeObject方法,定制输出json字符串使用LINQ to JSON。由json字符串转换为.net对象优先使用JsonConvert对象的DeserializeObject方法,然后也可以使用LINQ to JSON。

想了解更多相关内容请访问PHP中文网:JSON视频教程

The above is the detailed content of An article to let you know in detail what JSON is. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template