Repository navigation
Expand file tree
/
Copy pathJsonUtil.java
More file actions
112 lines (101 loc) · 2.9 KB
/
Copy pathJsonUtil.java
File metadata and controls
112 lines (101 loc) · 2.9 KB
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
package org.tron.core.net2.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import org.springframework.util.StringUtils;
import java.util.Map;
public class JsonUtil {
/**
* json字符串转换为map对象
*
* @param jsonString
* @return
*/
@SuppressWarnings("unchecked")
public static final Map<String, Object> json2Map(String jsonString) {
if (jsonString == null || jsonString.equals("")) {
return null;
}
try {
ObjectMapper om = new ObjectMapper();
return om.readValue(jsonString, Map.class);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
public static final <T> Map<String, T> json2Map(String jsonString, Class<T> clazz) {
return (Map<String, T>) json2Map(jsonString);
}
/**
* json字符串转换为制定类型的对象
*
* @param jsonString
* @param clazz
* @return
*/
public static final <T> T json2Obj(String jsonString, Class<T> clazz) {
if (StringUtils.isEmpty(jsonString) || clazz == null) {
return null;
}
try {
ObjectMapper om = new ObjectMapper();
return om.readValue(jsonString, clazz);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* json字符串转换为制定类型的对象
*
* @param jsonString
* @param clazz
* @return
*/
public static final <T> T fromJson(String jsonString, Class<T> clazz) {
if (StringUtils.isEmpty(jsonString) || clazz == null) {
return null;
}
try {
Gson gson = new Gson();
return gson.fromJson(jsonString, clazz);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* obj转换为json格式的string
*
* @param obj
* @return
*/
public static final String obj2String(Object obj) {
if (obj == null) {
return null;
}
ObjectMapper om = new ObjectMapper();
try {
return om.writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 获取不同层key的value,例如,获取2层key的value:{"key1":{"key2":"value"}}
*
* @param jsonString
* @param keys
* @return
*/
@SuppressWarnings("rawtypes")
public static final Object getValueFromJson(String jsonString, String... keys) {
Object object = json2Obj(jsonString, Map.class);
for (int i = 0; i < keys.length; i++) {
if ((object != null) && (object instanceof Map)) {
object = ((Map) object).get(keys[i]);
} else {
return null;
}
}
return object;
}
}