Json常用处理方式

概述

作为 面向对象 开发的程序员,每天的业务代码会遇到大量的 Json 处理。本文从最常见的几个类库 gson, fastjson, jackson 进行基本操作, 仅作记录。

基础准备

首先创建java对象用于测试

角色

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* @author 当我遇上你
* @公众号 当我遇上你
* @since 2020-06-10
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Role {

private String roleName;

}

这里我们创建一个复合嵌套对象user

1
2
3
4
5
6
7
8
9
10
11
/**
* @author 当我遇上你
* @公众号 当我遇上你
* @since 2020-06-10
*/
@Data
public class User {

private String userName;
private List<Role> roles;
}

用户组

1
2
3
4
5
6
7
8
9
10
11
12
/**
* @author 当我遇上你
* @公众号 当我遇上你
* @since 2020-06-11
*/
@Data
public class UserGroup implements Serializable {

private String groupName;
private Map<String, User> idNumber;

}

菜单

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* @author 当我遇上你
* @公众号 当我遇上你
* @since 2020-06-10
*/
@Data
@AllArgsConstructor
public class Menu {

@SerializedName("menu_name")
private String menuName;

}

部门

1
2
3
4
5
6
7
8
9
10
/**
* @author 当我遇上你
* @公众号 当我遇上你
* @since 2020-06-11
*/
@Data
@AllArgsConstructor
public class Dept {
private String deptName;
}

类型适配器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* @author 当我遇上你
* @公众号 当我遇上你
* @since 2020-06-11
*/
public class DeptAdapter implements JsonSerializer<Dept> {

@Override
public JsonElement serialize(Dept dept, Type type, JsonSerializationContext jsonSerializationContext) {

JsonObject deptObject = new JsonObject();
deptObject.addProperty("dept_name", dept.getDeptName());

return deptObject;
}
}

Gson

maven依赖

1
2
3
4
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>

单元测试

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
/**
* @author 当我遇上你
* @公众号 当我遇上你
* @since 2020-06-10
*/
class GsonTest {

/**
* {"userName":"admin","roles":[{"roleName":"系统管理员"},{"roleName":"普通管理员"}]}
*/
@Test
void toJson() {
Role role1 = new Role("系统管理员");
Role role2 = new Role("普通管理员");
User user = new User();
user.setUserName("admin");
user.setRoles(Arrays.asList(role1, role2));

// 对象转json
String json = new Gson().toJson(user);
System.out.println(json);
}

/**
* {"userName":"admin","roles":[{"roleName":"系统管理员"},{"roleName":"普通管理员"}]}
*/
@Test
void toJson2() {
Role role1 = new Role("系统管理员");
Role role2 = new Role("普通管理员");
User user = new User();
user.setUserName("admin");
user.setRoles(Arrays.asList(role1, role2));

String json = new GsonBuilder().create().toJson(user);
System.out.println(json);
}

/**
* User(userName=admin, roles=[Role(roleName=系统管理员), Role(roleName=普通管理员)])
*/
@Test
void fromJson() {
String json = "{\"userName\":\"admin\",\"roles\":[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}]}";
User user = new Gson().fromJson(json, User.class);
System.out.println(user);
}

/**
* admin
* {"userName":"admin","roles":{"roleName":"超级管理员"}}
*/
@Test
void createJsonObject() {

JsonObject role = new JsonObject();
role.addProperty("roleName", "超级管理员");

JsonObject user = new JsonObject();
user.addProperty("userName", "admin");
user.add("roles", role);

String username = user.get("userName").getAsString();
System.out.println(username);
System.out.println(user);
}

/**
* admin
*/
@Test
void json2Object() {

String json = "{\"userName\":\"admin\",\"roles\":[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}]}";

JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
String userName = jsonObject.get("userName").getAsString();
System.out.println(userName);
}


/**
* [{"roleName":"系统管理员"},{"roleName":"普通管理员"}]
*/
@Test
void list2Json() {

Role role1 = new Role("系统管理员");
Role role2 = new Role("普通管理员");
String json = new Gson().toJson(Arrays.asList(role1, role2));

System.out.println(json);
}

/**
* [Role(roleName=系统管理员), Role(roleName=普通管理员)]
*/
@Test
void json2List() {
String json = "[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}]";
List<Role> roles = new Gson().fromJson(json, new TypeToken<List<Role>>() {}.getType());

System.out.println(roles);
}

/**
* [{"roleName":"系统管理员"},{"roleName":"普通管理员"}]
*/
@Test
void json2Array() {
String json = "[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}]";
JsonArray jsonArray = JsonParser.parseString(json).getAsJsonArray();

System.out.println(jsonArray);
}

/**
* {"userName":"admin"}
*/
@Test
void map2Json() {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("userName", "admin");

String json = new Gson().toJson(hashMap);
System.out.println(json);
}

/**
* admin
*/
@Test
void json2Map() {
String json = "{\"userName\":\"admin\"}";
HashMap hashMap = new Gson().fromJson(json, new TypeToken<HashMap<String, String>>() {}.getType());

System.out.println(hashMap.get("userName"));
}


/**
* 默认的字段转换规则,字段名不变
* {"roleName":"超级管理员"}
*/
@Test
void setFieldNamingPolicy1() {

Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
.create();

Role role = new Role("超级管理员");
String json = gson.toJson(role);
System.out.println(json);
}

/**
* 将json中的字段名转换为首字母大写的格式
* {"RoleName":"超级管理员"}
*/
@Test
void setFieldNamingPolicy2() {

Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.create();

Role role = new Role("超级管理员");
String json = gson.toJson(role);
System.out.println(json);
}

/**
* 将json中的字段名转换为首字母大写,单词之间以空格分割的格式
* {"Role Name":"超级管理员"}
*/
@Test
void setFieldNamingPolicy3() {

Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES)
.create();

Role role = new Role("超级管理员");
String json = gson.toJson(role);
System.out.println(json);
}

/**
* 将json中的字段名转换为小写字母,单词之间以下划线分割的格式
* {"role_name":"超级管理员"}
*/
@Test
void setFieldNamingPolicy4() {

Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();

Role role = new Role("超级管理员");
String json = gson.toJson(role);
System.out.println(json);
}

/**
* 将json中的字段名转换为小写字母,单词之间以分隔线分割的格式
* {"role-name":"超级管理员"}
*/
@Test
void setFieldNamingPolicy5() {

Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES)
.create();

Role role = new Role("超级管理员");
String json = gson.toJson(role);
System.out.println(json);
}

/**
* 将json中的字段名转换为小写字母,单词之间以点分割的格式
* {"role.name":"超级管理员"}
*/
@Test
void setFieldNamingPolicy6() {

Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DOTS)
.create();

Role role = new Role("超级管理员");
String json = gson.toJson(role);
System.out.println(json);
}

/**
* 属性重命名
* {"menu_name":"系统管理"}
*/
@Test
void serializedName() {
Menu menu = new Menu("系统管理");

String json = new Gson().toJson(menu);
System.out.println(json);
}

/**
* {"dept_name":"产品研发部"}
*/
@Test
void adapter() {
Gson gson = new GsonBuilder()
//为Dept注册TypeAdapter
.registerTypeAdapter(Dept.class, new DeptAdapter())
.create();

Dept dept = new Dept("产品研发部");
String json = gson.toJson(dept);

System.out.println(json);
}

}

FastJson

maven依赖

1
2
3
4
5
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.68</version>
</dependency>

单元测试

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
public class FastJsonTest {

/**
* {"roles":[{"roleName":"系统管理员"},{"roleName":"普通管理员"}],"userName":"admin"}
*/
@Test
void toJson() {
Role role1 = new Role("系统管理员");
Role role2 = new Role("普通管理员");
User user = new User();
user.setUserName("admin");
user.setRoles(Arrays.asList(role1, role2));

String userJson = JSON.toJSONString(user);
System.out.println(userJson);
}

/**
* admin
* {"roles":[{"roleName":"系统管理员"},{"roleName":"普通管理员"}],"userName":"admin"}
*/
@Test
void jsonParse() {
String json = "{\"roles\":[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}],\"userName\":\"admin\"}";
JSONObject jsonObject = JSON.parseObject(json);

System.out.println(jsonObject.getString("userName"));
System.out.println(jsonObject);
}

/**
* [{"roleName":"系统管理员"},{"roleName":"普通管理员"}]
*/
@Test
void list2Json() {
Role role1 = new Role("系统管理员");
Role role2 = new Role("普通管理员");

String jsonString = JSON.toJSONString(Arrays.asList(role1, role2));

System.out.println(jsonString);
}

/**
* [{"roleName":"系统管理员"},{"roleName":"普通管理员"}]
*/
@Test
void json2List() {
String json = "[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}]";

JSONArray jsonArray = JSON.parseArray(json);
System.out.println(jsonArray);
}

/**
* [Role(roleName=系统管理员), Role(roleName=普通管理员)]
*/
@Test
void json2List2() {
String json = "[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}]";

List<Role> users = JSON.parseArray(json, Role.class);
System.out.println(users);
}

/**
* User(userName=admin, roles=[Role(roleName=系统管理员), Role(roleName=普通管理员)])
*/
@Test
void json2Bean() {
String json = "{\"roles\":[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}],\"userName\":\"admin\"}";

User user = JSON.parseObject(json, User.class);
System.out.println(user);
}

/**
* User(userName=admin, roles=[Role(roleName=系统管理员), Role(roleName=普通管理员)])
*/
@Test
void json2Bean2() {
String json = "{\"roles\":[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}],\"userName\":\"admin\"}";

User user = JSON.parseObject(json, new TypeReference<User>(){});
System.out.println(user);
}

/**
* {"userName":"admin"}
*/
@Test
void map2Json() {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("userName", "admin");

String jsonString = JSON.toJSONString(hashMap);
System.out.println(jsonString);
}

/**
* admin
*/
@Test
void json2Map() {
String json = "{\"userName\":\"admin\"}";

Map<String, String> map = (Map<String, String>) JSON.parse(json);
System.out.println(map.get("userName"));
}

/**
* {"userName":"admin"}
*/
@Test
void json2Map2() {
String json = "{\"userName\":\"admin\"}";

Map map = JSON.parseObject(json);
System.out.println(map);
}

/**
* {"groupName":"分组1","idNumber":{"001":{"roles":[{"roleName":"系统管理员"},{"roleName":"普通管理员"}],"userName":"admin"}}}
*/
@Test
void obj2Json() {
Role role1 = new Role("系统管理员");
Role role2 = new Role("普通管理员");
User user = new User();
user.setUserName("admin");
user.setRoles(Arrays.asList(role1, role2));

HashMap<String, User> map = new HashMap<>();
map.put("001", user);
UserGroup userGroup = new UserGroup();
userGroup.setGroupName("分组1");
userGroup.setIdNumber(map);

String jsonString = JSON.toJSONString(userGroup);
System.out.println(jsonString);
}

/**
* UserGroup(groupName=分组1, idNumber={001=User(userName=admin, roles=[Role(roleName=系统管理员), Role(roleName=普通管理员)])})
*/
@Test
void json2Obj() {
String json = "{\"groupName\":\"分组1\",\"idNumber\":{\"001\":{\"roles\":[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}],\"userName\":\"admin\"}}}";

UserGroup userGroup = JSON.parseObject(json, UserGroup.class);
System.out.println(userGroup);
}

}

Jackson

单元测试

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* @author 当我遇上你
* @公众号 当我遇上你
* @since 2020-06-11
*/
public class JacksonTest {

/**
* {"userName":"admin","roles":[{"roleName":"系统管理员"},{"roleName":"普通管理员"}]}
* @throws JsonProcessingException
*/
@Test
void Obj2Json() throws JsonProcessingException {
Role role1 = new Role("系统管理员");
Role role2 = new Role("普通管理员");
User user = new User();
user.setUserName("admin");
user.setRoles(Arrays.asList(role1, role2));

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(user);

System.out.println(json);
}

/**
* 需要无参构造方法
* User(userName=admin, roles=[Role(roleName=系统管理员), Role(roleName=普通管理员)])
* @throws JsonProcessingException
*/
@Test
void json2Obj() throws JsonProcessingException {
String json = "{\"userName\":\"admin\",\"roles\":[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}]}";

ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(json, User.class);
System.out.println(user);
}

/**
* admin
* @throws JsonProcessingException
*/
@Test
void json2Obj2() throws JsonProcessingException {
String json = "{\"userName\":\"admin\",\"roles\":[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}]}";

ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(json);

String userName = jsonNode.get("userName").asText();
System.out.println(userName);
}

/**
* [{"roleName":"系统管理员"},{"roleName":"普通管理员"}]
* @throws JsonProcessingException
*/
@Test
void list2Json() throws JsonProcessingException {
Role role1 = new Role("系统管理员");
Role role2 = new Role("普通管理员");

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(Arrays.asList(role1, role2));

System.out.println(json);
}

/**
* 需要无参构造方法
* [Role(roleName=系统管理员), Role(roleName=普通管理员)]
* @throws JsonProcessingException
*/
@Test
void json2List() throws JsonProcessingException {
String json = "[{\"roleName\":\"系统管理员\"},{\"roleName\":\"普通管理员\"}]";

ObjectMapper mapper = new ObjectMapper();
List<Role> roles = mapper.readValue(json, new TypeReference<List<Role>>() {
});

System.out.println(roles);
}
}

配置

  • json序列化去除value=null的key
1
@JsonInclude(JsonInclude.Include.NON_NULL)
  • 序列化重命名
1
2
3
4
5
6
7
8
9
/**
* Json反序列化: 将Json Data转化为Java Object
* Json的序列化: 将Java Object转化为JSON Data
*
* 将java中[name]字段序列化为json中的[NAME]字段.
* 注意: 反序列化时也必须用[NAME]字段, 否则会报: UnrecognizedPropertyException: Unrecognized field "name"
*/
@JsonProperty("NAME")
private String name;
  • 反序列化重命名
1
2
3
4
5
/**
* 将json中的age_alias字段反序列化为java的[age]字段
*/
@JsonAlias("age_alias")
private Integer age;
  • LocalDateTime格式化
1
2
3
4
5
6
7
8
/**
* @DateTimeFormat 是将String转换成Date,一般前台给后台传值时用
* @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") 将Date转换成String, 一般后台传值给前台时
* 东八区(UTC/GMT+08:00)比世界协调时间(UTC)/格林尼治时间(GMT)快8小时
*/
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime date;
  • Java实体驼峰序列化为下划线(全局配置)
1
2
3
4
5
6
7
ObjectMapper objectMapper = new ObjectMapper();
// 反序列化时, 当JSON字符串某个属性在Java POJO对象中未定义时,是否解析失败,默认值为true
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 表明该类为NULL的字段不参加序列化
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// Java实体驼峰序列化为下划线
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
  • 序列化携带 class 信息
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package cn.idea360.jpa;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.Serializable;

/**
* @author cuishiying
*/
@Slf4j
class JsonTest {

@Data
public static class Student implements Serializable {
private String name;
}

@Data
public static class Child implements Serializable {
private String name;
}

@Data
public static class Father implements Serializable {
private Child[] children;
}

@Data
public static class Teacher implements Serializable {

/**
* 序列化携带类信息
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "@class")
private Student student;

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "@class")
private Child[] children;
}

private Student student;
private Father father;
private Teacher teacher;

@BeforeEach
void init() {
student = new Student();
student.setName("admin");
Child child = new Child();
child.setName("张三");

father = new Father();
father.setChildren(new Child[]{child});

teacher = new Teacher();
teacher.setStudent(student);
teacher.setChildren(new Child[]{child});
}

@Test
void toJson() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(student);
log.info(json);
}

@Test
void toJsonWithClass1() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(teacher);
log.info(json);
}

@Test
void toJsonWithClass2() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
// 序列化携带类信息
objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE).setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
String json = objectMapper.writeValueAsString(father);
log.info(json);
Father father = objectMapper.readValue(json, Father.class);
log.info(String.valueOf(father));
}
}

最后

本文到此结束,感谢阅读。如果您觉得不错,请关注公众号【当我遇上你】,您的支持是我写作的最大动力。