JsonUtil.java
6.85 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
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
package com.cjs.cms.util.lang;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.databind.util.JSONPObject;
/**
* JSON转换工具类
*
* @author trunks
* @version $Id: JsonUtils.java, v 0.1 2014-5-27 trunks Exp $
*/
public class JsonUtil {
private static Logger logger = LogManager.getLogger();
private static ObjectMapper mapper = null;
static {
mapper = new ObjectMapper();
// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
//允许key没有使用双引号的json
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
//零时区
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//format.setTimeZone(TimeZone.getTimeZone("UTC"));
mapper.setDateFormat(format);
//输出格式化
mapper.configure(SerializationFeature.INDENT_OUTPUT, false);
}
/**
* 将对象转换成JSON字符串
* @param obj 目标对象
* @return 字符串,转换失败时返回null
*/
public static String toJson(Object obj) {
try {
return mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
logger.error("write to json string error:" + obj, e);
return null;
}
}
/**
* 将单个键值对转换成JSON字符串,用于返回只有一个键值对json时的便捷方法
* @param obj 目标对象
* @return 字符串,转换失败时返回null
*/
public static String toJson(Object key, Object value) {
Map<Object, Object> map = new HashMap<Object, Object>();
map.put(key, value);
try {
return mapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
logger.error("write to json string error:" + map, e);
return null;
}
}
/**
* 转换JSON对象为Ext表单提交成功的方式<br />
* ex.{"success":"false","data":{"name":"名称已存在"}}
*
* @param obj 错误信息,若用map,Key若为表单项的name,则会自动在对应表单项显示错误信息
*/
public static String toFormJson(Object obj, boolean success) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("success", success);
map.put("data", obj);
try {
return mapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
logger.error("write to json string error:" + obj, e);
return null;
}
}
/**
* 转换JSON对象为EasyUI GridView分页格式<br />
* @param rows 记录集合
* @param total 记录数
* @param footer 页脚
*/
public static String toPageJson(List<?> rows, int total, Object... footer) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("rows", rows);
map.put("total", total);
if (footer != null && footer.length > 0 && footer[0] != null) {
map.put("footer", footer);
}
try {
return mapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
logger.error("write to json string error:" + rows, e);
return null;
}
}
/**
* 转换分页查询结果
*
* @param list 结果集
* @param total 记录数
*/
public static String writePageJson(Object list, Object total) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("list", list);
map.put("total", total);
try {
return mapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
logger.error("write to json string error:" + list, e);
return null;
}
}
/**
* 反序列化POJO或简单Collection如List<String>.
*
* 如果JSON字符串为Null或"null"字符串, 返回Null.
* 如果JSON字符串为"[]", 返回空集合.
*
* 如需反序列化复杂Collection如List<MyBean>, 请使用fromJson(String, JavaType)
*
* @see #fromJson(String, JavaType)
*/
public static <T> T fromJson(String jsonString, Class<T> clazz) {
if (StringUtils.isBlank(jsonString)) {
return null;
}
try {
return mapper.readValue(jsonString, clazz);
} catch (IOException e) {
logger.error("parse json string error:" + jsonString, e);
return null;
}
}
/**
* 反序列化复杂Collection如List<Bean>
* @param jsonString
* @param collectionType 集合类型
* @param elementType 集合内元素类型
* @return 转换失败时返回 null
*/
public static <L extends Collection<E>, E> L fromJson(String jsonString,
Class<L> collectionClass,
Class<E> elementClass) {
if (StringUtils.isBlank(jsonString)) {
return null;
}
try {
CollectionType type = mapper.getTypeFactory().constructCollectionType(collectionClass,
elementClass);
return mapper.readValue(jsonString, type);
} catch (Exception e) {
logger.error("parse json string error:" + jsonString, e);
return null;
}
}
/**
* 当JSON里只含有Bean的部分属性,更新一个已存在Bean,只覆盖该部分的属性.
*/
public static void update(String jsonString, Object object) {
try {
mapper.readerForUpdating(object).readValue(jsonString);
} catch (JsonProcessingException e) {
logger.error("update json string:" + jsonString + " to object:" + object + " error.",
e);
} catch (IOException e) {
logger.error("update json string:" + jsonString + " to object:" + object + " error.",
e);
}
}
/**
* 输出JSONP格式数据
*/
public static String toJsonP(String functionName, Object object) {
return toJson(new JSONPObject(functionName, object));
}
}