浅谈Java后台对JSON格式的处理操作

时间:2021-11-22 00:02:59

1. 将对象转换为JSON字符串,返回值为一个JSON字符串

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static String toJson(Object value) {
 
try {
 
return mapper.writeValueAsString(value);
 
} catch (Exception e) {
 
e.printStackTrace();
 
}
 
return null;
 
}

2.  将JSON字符串转换为实体对象,返回值为实体对象

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public static <T> T toObject(String json, Class<T> valueType) {
 
Assert.hasText(json);
 
Assert.notNull(valueType);
 
try {
 
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
mapper.setDateFormat(dateFormat);
 
return mapper.readValue(json, valueType);
 
} catch (Exception e) {
 
e.printStackTrace();
 
}
 
return null;

以上这篇浅谈Java后台对JSON格式的处理操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。