JavaScript Object Notation -JavaScript
用于存储和交换文本信息的语法,进行数据的传输,JSON比 XML 更小、更快,更易解析。
var person = {"name": "张三", age: 23, 'gender': true};
var ps = [{"name": "张三", "age": 23, "gender": true},
{"name": "李四", "age": 24, "gender": true},
{"name": "王五", "age": 25, "gender": false}];
var b='{"name":"2323","sex":"afasdf","age":"6262"}';//json字符串
console.log(b);//{"name":"2323","sex":"afasdf","age":"6262"}
alert(typeof(b));//string
将数据结构或是对象 转换为 二进制串(字节序列)的过程 用来数据的传输 (把数据装换成json字符串 后端配合@reponseBody来进行数据的接受和传递)
后端是Java对象,想用JSON的格式将数据传输,就要进行序列化操作。
Java对象序列化了才可以在网络上传输,或者保存到硬盘上。
序列化完就变成了json字符串了 通过jackson这个序列化框架序列化
在后端通过在controller上面加@reponseBody注解 将从service层获取到的java对象转化为json格式对象,传输到前端
在controller的请求参数前加@reponseBody 就可以将前端传过来的json格式的数据接收
这个ObjectMapper对象是jackson包下面的,这是他的依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.3</version>
</dependency>
//类属性,
private static final ObjectMapper MAPPER = new ObjectMapper();
//序列化-----userMapList是List的格式,现在我们需要将List集合序列化为json字符串
MAPPER.writeValueAsString(userMapList);
//反序列化---json格式的字符串要反序列化为对象
MAPPER.readValue(你要反序列化的json字符串,new TypeReference<要反序列化为什么对象类型,例如 User.class>() {});
序列化:将Js中的对象转化成Json格式,序列化的两个参数:过滤器和选项。
var person = {
username: ‘luohao’,
password: 123456,
location: ‘whu’
}
参数是一个数组,出现在数组中的属性才会序列化,其余属性忽略不计。
var json = JSON.stringify(person, [‘username’, ‘password’]);
console.log(json);
{“username”:“luohao”,“password”:123456}
var person = {
username: ‘luohao’,
password: 123456,
location: ‘whu’,
hometown: ‘wuhan’,
}
var json = JSON.stringify(person, function filter(key, value) {
switch(key) {
case ‘location’: return undefined;
case ‘hometown’: return undefined;
default: return value;
}
});
console.log(json);
{“username”:“luohao”,“password”:123456}
JSON.stringify()中的第三个参数表示缩进的空格数,
这样传输的数据可读性比较好。
var person = {
username: ‘luohao’,
password: 123456,
location: {
province: ‘hubei’,
city: ‘wuhan’,
county: ‘qichun’
},
hometown: ‘wuhan’,
}
var json = JSON.stringify(person, function filter(key, value) {
switch(key) {
case ‘hometown’: return undefined;
default: return value;
}
});
console.log(json);
{“username”:“luohao”,“password”:123456,“location”:{“province”:“hubei”,“city”:“wuhan”,“county”:“qichun”}}
var person = {
username: ‘luohao’,
password: 123456,
location: {
province: ‘hubei’,
city: ‘wuhan’,
county: ‘qichun’
},
hometown: ‘wuhan’,
}
var json = JSON.stringify(person, function filter(key, value) {
switch(key) {
case ‘hometown’: return undefined;
default: return value;
}
}, 2);
console.log(json);
{
“username”: “luohao”,
“password”: 123456,
“location”: {
“province”: “hubei”,
“city”: “wuhan”,
“county”: “qichun”
}
}