Jackson
# Jackson
坐标
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Jackson 是把 JSON 转为 java 对象或者集合的一个工具类
SpringMVC 转换默认使用 Jackson
- ObjectMapper 实现 JSON 字符串和对象之间的转换
- writeValueAsString (object obj) 将 java 对象转为 json 字符串
<T>T readValue(String json,class<T>valueTType) 将 json 字符串转为 java 对象<T>T readValue (String json,TypeReferncevalueTType) 将 json 字符串转为 java 对象
- TypeReference 对集合泛型的反序列化
private ObjectMapper mapper =new ObjectMapper();
user user = new user("张三",23);
//对象转json
String json = mapper.writeValueAsString(user);
System.out.println(json);
//json转对象
user user1 = mapper.readValue(json, user.class);
System.out.println(user1);
//map转json
HashMap<String,String> map =new HashMap<>();
map.put("姓名","张三");
map.put("性别","男");
String s = mapper.writeValueAsString(map);
System.out.println(s);
//json转map
HashMap<String,String> hashMap = mapper.readValue(s, HashMap.class);
System.out.println(hashMap);
//map<String,user> 转json
HashMap<String,user> map2 =new HashMap<>();
map2.put("一班",new user("张三",23));
map2.put("二班",new user("李四",23));
String s1 = mapper.writeValueAsString(map2);
System.out.println(s1);
//json转 map<String,user>
HashMap<String,user> map3=mapper.readValue(s1,new TypeReference<HashMap<String,user>>(){});
System.out.println(map3);
//List<String> 换json
ArrayList<String> list=new ArrayList<>();
list.add("张三");
list.add("李四");
String s2 = mapper.writeValueAsString(list);
System.out.println(s2);
//List<String> 转json
ArrayList arrayList = mapper.readValue(s2, ArrayList.class);
System.out.println(arrayList);
//List<user> 换json
ArrayList<user> list2=new ArrayList<>();
list2.add(new user("张三",23));
list2.add(new user("王五",22));
String s3 = mapper.writeValueAsString(list2);
System.out.println(s3);
//List<user> 转json
ArrayList<user> arrayList2 = mapper.readValue(s3, new TypeReference<ArrayList<user>>(){});
System.out.println(arrayList2);
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
编辑 (opens new window)
上次更新: 2023/12/06, 01:31:48