-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJavaUtils-JsonUtil.template
executable file
·76 lines (68 loc) · 1.78 KB
/
JavaUtils-JsonUtil.template
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
package com.sd.packagename.common.util;
import java.util.List;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @Created with Atom
* @author @author@
* @time @now@
* @description
* json转换工具类
*
**/
public class JsonUtils {
// 定义jackson对象
private static final ObjectMapper MAPPER = new ObjectMapper();
/**
* 将对象转换成json字符串。
* Title: pojoToJson
* Description:
* @param data
* @return
*/
public static String objectToJson(Object data) {
try {
String string = MAPPER.writeValueAsString(data);
return (string);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return (null);
}
/**
* 将json结果集转化为对象
*
* @param jsonData json数据
* @param clazz 对象中的object类型
* @return
*/
public static < T > T jsonToPojo(String jsonData, Class < T > beanType) {
try {
T t = MAPPER.readValue(jsonData, beanType);
return (t);
} catch (Exception e) {
e.printStackTrace();
}
return (null);
}
/**
* 将json数据转换成pojo对象list
* Title: jsonToList
* Description:
* @param jsonData
* @param beanType
* @return
*/
public static < T > List < T > jsonToList(String jsonData, Class < T > beanType) {
JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
try {
List < T > list = MAPPER.readValue(jsonData, javaType);
return (list);
} catch (Exception e) {
e.printStackTrace();
}
return (null);
}
}