JS-json

JSON

JSON(JavaScript Object Notation,js对象简谱)

一个特定的字符串语法结构

JSON格式的字符串,在前后端都可以很方便的和对象之间进行转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script>
// json中,属性值和属性名都需要用双引号包好,数字可以不做处理
// 属性值可以是数组,对象,对象数组
// var personStr ='{"属性名":"属性值","属性名":"属性值"}'
// 在json中主要使用属性传递数据,不讨论方法的传递

//创建一个json格式的字符串
var personStr =
'{"name":"张三","age":10,"dog":{"dname":"小花"},"loveSingers" :["张晓明","王晓东","李小黑"],"friends":[{"fname":"赵四儿"},{"fname":"玉田"},{"fname":"王小蒙"}] }';
var person = JSON.parse(personStr);
console.log(personStr);
console.log(person);
//可以通过逐层打点的方式,访问每一个属性

//也可以将对象转换为json串
var personstr1 = JSON.stringify(person);
console.log(personstr1);
</script>

在后端,同样可使用jackson工具对json串进行转换操作

我们需要使用到Jackson来对json串进行转换

Central Repository: com/fasterxml/jackson/core (maven.org)

1
2
3
4
5
6
7
8
9
@Test
public void test() {
ObjectMapper objectMapper = new ObjectMapper();
String personStr = objectMapper.writeValueAsString(person);//将 person对象转成json串

ObjectMapper objectMapper1 = new ObjectMapper();
Person person = objectMapper1.readValue(PersonStr, Person.class);//将personStr字符串转成Person类的对象person

}

Map,List,数组的JSON串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@Test
public void test1() throws JsonProcessingException {
//map集合转为JSON串
Map map = new HashMap();
map.put("a", "valuea");
map.put("b", "valueb");
map.put("c", "valuec");

ObjectMapper objectMapper = new ObjectMapper();
System.out.println(objectMapper.writeValueAsString(map));//{"a":"valuea","b":"valueb","c":"valuec"}
}

@Test
public void test2() throws JsonProcessingException {
//List集合转为JSON串
List list = new ArrayList();
list.add("a");
list.add("b");
list.add("c");
ObjectMapper objectMapper = new ObjectMapper();
System.out.println(objectMapper.writeValueAsString(list));//["a","b","c"]
}

@Test
public void test3() throws JsonProcessingException {
String[] data = {"a", "b", "c"};
ObjectMapper objectMapper = new ObjectMapper();
System.out.println(objectMapper.writeValueAsString(data));//["a","b","c"]
}


JS-json
http://blog.170827.xyz/2024/03/28/JS-json/
作者
XIAOBAI
发布于
2024年3月28日
许可协议