1.Json的格式
json 是一种与语言无关数据交换的格式,作用:使用ajax进行前后台数据交换,移动端与服务端的数据交换。
json是JS的原生内容,也就意味着JS可以直接取出json对象中的数据。
2.Json规则
1)映射用冒号(“:”)表示。名称:值
2)并列的数据之间用逗号(“,”)分隔。名称1:值1,名称2:值2
3)
4)
[
{名称1:值,名称2:值2},
{名称1:值,名称2:值2}
]
5)元素值可具有的类型:string, number, object, array, true, false, null
json有两种格式:
1)对象格式:{“key1”: obj,“key2”: obj,“key3”: obj...}
2) 数组格式:[obj,obj,obj...]
例:
User对象
{"userName" : "zhangsan","userAge" : "20","passWord" : "123456","addr":"北京","acount":{"money":"3333","time":"2018-08-22"}}
List<Product>
[{"pId":"10","pName":"魅族16","pPrice":"3500"},{"pId":"12","pName":"魅族17","pPrice":"3500"},{"pId":"13","pName":"魅族18","pPrice":"3700"}...]
注意:对象格式和数组格式可以嵌套。
json的key是字符串,value是Object。
对象格式
<script language="JavaScript">
/**
* 案例一
* {key:value,key:value}
*
* class Person{
* String firstName = "张";
* String lastName = "三丰";
* Integer age = 100;
* }
*
* Person p = new Person();
* System.out.println(p.firstName);
*/
var person = {"firstName":"张","lastName":"三丰","age":100};
//取出firstName
alert(person.firstName);
//取出laetName
alert(person.lastName);
//取出age
alert(person.age);
</script>
数组格式
<script language="JavaScript">
/**
* 案例二
* [{key:value,key:value},{key:value,key:value}]
*
*/
var persons = [{"firstName":"张","lastName":"三丰","age":100},{"firstName":"李","lastName":"三丰","age":200},{"firstName":"马","lastName":"三丰","age":300}]
//取出firstName == "李"
alert(persons[1].firstName);
</script>
对象中有数组
<script language="JavaScript">
/**
* 案例三
* {
* "param":[{key:value,key:value},{key:value,key:value}]
* }
*
*
*/
var json = {
"baobao":[
{"name":"小双","age":22,"addr":"扬州"},
{"name":"小茹","age":22,"addr":"苏州"},
("name":"小青","age":22,"addr":"徐州")
]
};
//取name == 小茹
alert(json.baobao[1].name);
</script>
对象中多数组
<script language="JavaScript">
/**
* 案例四
* {
* "param1":[{key:value,key:value},{key:value,key:value}],
* "param2":[{key:value,key:value},{key:value,key:value}],
* "param3":[{key:value,key:value},{key:value,key:value}]
* }
*
*
*/
var json = {
"baobao":[
{"name":"小双","age":22,"addr":"扬州"},
{"name":"小茹","age":22,"addr":"苏州"},
("name":"小青","age":22,"addr":"徐州")
],
"haohao": [
{"name":"小爽","age":22,"addr":"南京"},
{"name":"小洁","age":25,"addr":"苏州"},
("name":"小青","age":24,"addr":"徐州")
]
};
//取"小洁"
alert(json.haohao[1].name);
</script>
混合嵌套
<script language="JavaScript">
/**
* 案例五
* {
* "param1":"value1",
* "param2":{},
* "param3":[{key:value,key:value},{key:value,key:value}]
* }
*
*
*/
var json = {
"key1":"value1",
"key2":{"firstName":"赵","lastName":"三丰","age":100},
"key3": [{"firstName":"张","lastName":"三丰","age":100},{"firstName":"李","lastName":"三丰","age":200},{"firstName":"马","lastName":"三丰","age":300}]
//取"赵"
alert(json.key2.firstName);
</script>
};