当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JSON详解

JSON详解

2019年02月16日  | 移动技术网IT编程  | 我要评论
JSON详解 JSON详解 阅读目录 JSON的两种结构 认识JSON字符串 在JS中如何使用JSON 在.NET中如何使用JSON 总结 JSON的全称是”JavaScript Object Notation”,意思是JavaScript对象表示法,它是一种基于文本,独立于语言的轻量级数据交换格式 ...

json的全称是”javascript object notation”,意思是javascript对象表示法,它是一种基于文本,独立于语言的轻量级数据交换格式。xml也是一种数据交换格式,为什么没有选择xml呢?因为xml虽然可以作为跨平台的数据交换格式,但是在js(javascript的简写)中处理xml非常不方便,同时xml标记比数据多,增加了交换产生的流量,而json没有附加的任何标记,在js中可作为对象处理,所以我们更倾向于选择json来交换数据。这篇文章主要从以下几个方面来说明json。

1,json的两种结构
2,认识json字符串
3,在js中如何使用json
4,在.net中如何使用json
5,总结

json的两种结构

json有两种表示结构,对象和数组。
对象结构以”{”大括号开始,以”}”大括号结束。中间部分由0或多个以”,”分隔的”key(关键字)/value(值)”对构成,关键字和值之间以”:”分隔,语法结构如代码。

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

其中关键字是字符串,而值可以是字符串,数值,true,false,null,对象或数组

数组结构以”[”开始,”]”结束。中间由0或多个以”,”分隔的值列表组成,语法结构如代码。

复制代码
[
    {
        key1:value1,
        key2:value2 
    },
    {
         key3:value3,
         key4:value4   
    }
]
复制代码

认识json字符串

之前我一直有个困惑,分不清普通字符串,json字符串和json对象的区别。经过一番研究终于给弄明白了。比如在js中。

字符串:这个很好解释,指使用“”双引号或’’单引号包括的字符。例如:var comstr = 'this is string';
json字符串:指的是符合json格式要求的js字符串。例如:var jsonstr = "{studentid:'100',name:'tmac',hometown:'usa'}";
json对象:指符合json格式要求的js对象。例如:var jsonobj = { studentid: "100", name: "tmac", hometown: "usa" };

在js中如何使用json

json是js的一个子集,所以可以在js中轻松地读,写json。读和写json都有两种方法,分别是利用”.”操作符和“[key]”的方式。
我们首先定义一个json对象,代码如下。

复制代码
var obj = {
            1: "value1",
            "2": "value2",
            count: 3,
            person: [ //数组结构json对象,可以嵌套使用
                        {
                            id: 1,
                            name: "张三"
                        },
                        {
                            id: 2,
                            name: "李四"
                        }
                   ],
            object: { //对象结构json对象
                id: 1,
                msg: "对象里的对象"    
            }
        };
复制代码

1,从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"])
        }
复制代码

2,向json中写数据

比如要往json中增加一条数据,代码如下:

function add() { 
            //往json对象中增加了一条记录
            obj.sex= "男" //或者obj["sex"]="男"
        }

增加数据后的json对象如图:

3,修改json中的数据

我们现在要修改json中count的值,代码如下:

function update() {
            obj.count = 10; //或obj["count"]=10
        }

修改后的json如图。

4,删除json中的数据

我们现在实现从json中删除count这条数据,代码如下:

function delete() {
            delete obj.count;
        }

删除后的json如图

可以看到count已经从json对象中被删除了。

5,遍历json对象

可以使用for…in…循环来遍历json对象中的数据,比如我们要遍历输出obj对象的值,代码如下:

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

程序输出结果为:

在.net中如何使用json

说到在.net中使用json,就不得不提到json.net,它是一个非常著名的在.net中处理json的工具,我们最常用的是下面两个功能。

1,通过序列化将.net对象转换为json字符串

在web开发过程中,我们经常需要将从数据库中查询到的数据(一般为一个集合,列表或数组等)转换为json格式字符串传回客户端,这就需要进行序列化,这里用到的是jsonconvert对象的serializeobject方法。其语法格式为:jsonconvert.serializeobject(object),代码中的”object”就是要序列化的.net对象,序列化后返回的是json字符串。

比如,现在我们有一个tstudent的学生表,表中的字段和已有数据如图所示

从表中我们可以看到一共有五条数据,现在我们要从数据库中取出这些数据,然后利用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);
            }
        }
复制代码

输出结果

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

 

2,使用linq to json定制json数据

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

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

复制代码
{ 
    "total": 5, //记录总数
    "rows":[
        //json格式的数据列表
    ]
}
复制代码

使用linq to json前,需要引用newtonsoft.json的dll和using 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();
            }
        }
复制代码

输出结果为:

 

3,处理客户端提交的json数据

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

[
    {studentid:"100",name:"aaa",hometown:"china"},
    {studentid:"101",name:"bbb",hometown:"us"},
    {studentid:"102",name:"ccc",hometown:"england"}
]

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

复制代码
protected void page_load(object sender, eventargs e)
        {
            string inputjsonstring = @"
                [
                    {studentid:'100',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='80'>studentid</td><td width='100'>name</td><td width='100'>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;
        }
复制代码

输出结果:

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

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

总结

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

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网