您的位置:首页 > Web前端 > JavaScript

AJAX和JSON—json

2017-01-31 00:43 369 查看

JSON简介

JSON:JavaScript 对象表示法(JavaScript Object Notation)。
JSON是存储和交换文本信息的语法。类似XML。
JSON比XML更小、更快,更易解析。

JSON语法格式

JSON的语法格式主要采用键值对(key:value)的形式。

JSON 对象

{ "name":"张三" , "age":22}


JSON 数组

{
"student": [
{ "name":"张三" , "age":22 },
{ "name":"李四" , "age":23 },
{ "name":"王五" , "age":24 }
]
}


JSON 嵌套

{
"student": [
{ "name":"张三" , "age":22 ,"score":{"chinese":90,"math":100,"english":80} },
{ "name":"李四" , "age":23 ,"score":{"chinese":70,"math":90, "english":90} },
{ "name":"王五" , "age":24 ,"score":{"chinese":80,"math":60, "english":90} }
]
}


把 Json 串换成 Json 对象
var dataObj=eval("("+data+")");//转换为 json 对象

var dataObj=eval("("+xmlHttp.responseText+")");


JSON第三方jar包引入

在不使用第三方jar包之前,存储数据如下所示(由于在引号内使用引号,需要通过\进行转义):

String resultJson="{\"name\":\"张三\",\"age\":22}";


此时需要存储JSON数组或进行其它复杂格式时,较为麻烦。故引入第三方jar包:json-lib,这些jar包如图所示:





1.使用json-lib创建JSON对象

JSONObject resultJson=new JSONObject();
resultJson.put("name", "张三");
resultJson.put("age", 22);


2.使用json-lib创建JSON数组

JSONObject resultJson=new JSONObject();

JSONArray jsonArray=new JSONArray();
JSONObject jsonObject1=new JSONObject();
jsonObject1.put("name", "张三");
jsonObject1.put("age", 22);
JSONObject jsonObject2=new JSONObject();
jsonObject2.put("name", "李四");
jsonObject2.put("age", 23);
JSONObject jsonObject3=new JSONObject();
jsonObject3.put("name", "王五");
jsonObject3.put("age", 24);
jsonArray.add(jsonObject1);
jsonArray.add(jsonObject2);
jsonArray.add(jsonObject3);

resultJson.put("students", jsonArray);


3.使用json-lib创建JSON嵌套

JSONObject resultJson=new JSONObject();

JSONArray jsonArray=new JSONArray();
JSONObject jsonObject1=new JSONObject();
jsonObject1.put("name", "张三");
jsonObject1.put("age", 22);

JSONObject scoreObject1=new JSONObject();
scoreObject1.put("chinese", 90);
scoreObject1.put("math", 100);
scoreObject1.put("english", 80);
jsonObject1.put("score", scoreObject1);

JSONObject jsonObject2=new JSONObject();
jsonObject2.put("name", "李四");
jsonObject2.put("age", 23);

JSONObject scoreObject2=new JSONObject();
scoreObject2.put("chinese", 70);
scoreObject2.put("math", 90);
scoreObject2.put("english", 90);
jsonObject2.put("score", scoreObject2);

JSONObject jsonObject3=new JSONObject();
jsonObject3.put("name", "王五");
jsonObject3.put("age", 24);

JSONObject scoreObject3=new JSONObject();
scoreObject3.put("chinese", 80);
scoreObject3.put("math", 60);
scoreObject3.put("english", 90);
jsonObject3.put("score", scoreObject3);

jsonArray.add(jsonObject1);
jsonArray.add(jsonObject2);
jsonArray.add(jsonObject3);

resultJson.put("students", jsonArray);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: