JsonMapper.java 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. package cn.com.qmth.ac.util;
  2. import com.fasterxml.jackson.annotation.JsonInclude.Include;
  3. import com.fasterxml.jackson.core.JsonParser;
  4. import com.fasterxml.jackson.core.JsonProcessingException;
  5. import com.fasterxml.jackson.core.type.TypeReference;
  6. import com.fasterxml.jackson.databind.*;
  7. import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;
  8. import com.fasterxml.jackson.databind.module.SimpleModule;
  9. import com.fasterxml.jackson.databind.util.JSONPObject;
  10. import org.apache.commons.lang3.StringUtils;
  11. import org.slf4j.Logger;
  12. import org.slf4j.LoggerFactory;
  13. import java.io.IOException;
  14. import java.text.SimpleDateFormat;
  15. import java.util.*;
  16. /**
  17. * 简单封装Jackson,实现JSON 与 Java Object互相转换的Mapper 封装不同的输出风格, 使用不同的builder函数创建实例
  18. */
  19. @SuppressWarnings("unchecked")
  20. public class JsonMapper {
  21. private static final Logger LOG = LoggerFactory.getLogger(JsonMapper.class);
  22. private ObjectMapper mapper;
  23. /**
  24. * 默认构造JsonMapper
  25. */
  26. public JsonMapper() {
  27. this(null);
  28. }
  29. /**
  30. * 创建只输出初始值被改变的属性到Json字符串的Mapper, 最节约的存储方式
  31. */
  32. public static JsonMapper nonDefaultMapper() {
  33. return new JsonMapper(Include.NON_DEFAULT);
  34. }
  35. /**
  36. * 创建只输出非Null且非Empty的属性到Json字符串的Mapper
  37. */
  38. public static JsonMapper nonEmptyMapper() {
  39. return new JsonMapper(Include.NON_EMPTY);
  40. }
  41. /**
  42. * 创建只输出非Null的属性到Json字符串的Mapper
  43. */
  44. public static JsonMapper nonNullMapper() {
  45. return new JsonMapper(Include.NON_NULL);
  46. }
  47. /**
  48. * 构造JsonMapper
  49. */
  50. public JsonMapper(Include include) {
  51. mapper = new ObjectMapper();
  52. SimpleModule module = new SimpleModule();
  53. module.addDeserializer(String.class, new StdScalarDeserializer<String>(String.class) {
  54. @Override
  55. public String deserialize(JsonParser jsonParser, DeserializationContext ctx)
  56. throws IOException, JsonProcessingException {
  57. // 去掉头尾空格
  58. return jsonParser.getValueAsString() != null ? jsonParser.getValueAsString().trim() : null;
  59. }
  60. });
  61. mapper.registerModule(module);
  62. // 设置输出时包含属性的风格
  63. if (include != null) {
  64. mapper.setSerializationInclusion(include);
  65. }
  66. // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
  67. mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
  68. // 忽略无法转换的对象
  69. mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
  70. // 设置默认日期格式
  71. mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
  72. }
  73. /**
  74. * Object可以是POJO,也可以是Collection或数组 如果对象为Null, 返回"null" 如果集合为空集合, 返回"[]"
  75. */
  76. public String toJson(Object object) {
  77. if (object == null) {
  78. return null;
  79. }
  80. try {
  81. return mapper.writeValueAsString(object);
  82. } catch (IOException e) {
  83. LOG.error("toJson error!" + e.getMessage(), e);
  84. return null;
  85. }
  86. }
  87. /**
  88. * Object 转换为 Json(美化版) 若对象为 null 或 转换异常时,返回null 若集合为空集合,返回[]
  89. */
  90. public String toPrettyJson(Object object) {
  91. if (object == null) {
  92. return null;
  93. }
  94. try {
  95. return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
  96. } catch (IOException e) {
  97. LOG.error("toPrettyJson error! " + e.getMessage(), e);
  98. return null;
  99. }
  100. }
  101. /**
  102. * 反序列化POJO或简单Collection如List<String> 如果JSON字符串为Null或"null"字符串, 返回Null
  103. * 如果JSON字符串为"[]", 返回空集合 如需反序列化复杂Collection如List<MyBean>,
  104. * 请使用parseJson(String, JavaType)
  105. */
  106. public <T> T parseJson(String jsonStr, Class<T> clazz) {
  107. if (StringUtils.isEmpty(jsonStr)) {
  108. return null;
  109. }
  110. try {
  111. return mapper.readValue(jsonStr, clazz);
  112. } catch (IOException e) {
  113. LOG.error("parseJson error!" + e.getMessage(), e);
  114. return null;
  115. }
  116. }
  117. /**
  118. * 反序列化复杂Collection如List<Bean>,
  119. * 先使用createCollectionType()或constructMapType()构造类型, 然后调用本函数
  120. */
  121. public <T> T parseJson(String jsonStr, JavaType javaType) {
  122. if (StringUtils.isEmpty(jsonStr)) {
  123. return null;
  124. }
  125. try {
  126. return (T) mapper.readValue(jsonStr, javaType);
  127. } catch (IOException e) {
  128. LOG.error("parseJson error!" + e.getMessage(), e);
  129. return null;
  130. }
  131. }
  132. /**
  133. * 反序列化复杂的对象,如Page<Bean>
  134. */
  135. public <T> T parseJson(String jsonStr, TypeReference javaType) {
  136. if (StringUtils.isEmpty(jsonStr)) {
  137. return null;
  138. }
  139. try {
  140. return (T) mapper.readValue(jsonStr, javaType);
  141. } catch (IOException e) {
  142. LOG.error("parseJson error!" + e.getMessage(), e);
  143. return null;
  144. }
  145. }
  146. /**
  147. * Json 转换为 T[] 若Json字符串为 null 或 empty 或 转换异常时,返回null
  148. */
  149. public <T> T[] toArray(String jsonStr, Class<T> clazz) {
  150. JavaType javaType = this.constructArrayType(clazz);
  151. return this.parseJson(jsonStr, javaType);
  152. }
  153. /**
  154. * Json to List
  155. */
  156. public <T> List<T> toList(String jsonStr, Class<T> bean) {
  157. if (StringUtils.isEmpty(jsonStr)) {
  158. return null;
  159. }
  160. try {
  161. JavaType javaType = constructCollectionType(List.class, bean);
  162. return mapper.readValue(jsonStr, javaType);
  163. } catch (IOException e) {
  164. LOG.error("parseJson error!" + e.getMessage(), e);
  165. return null;
  166. }
  167. }
  168. /**
  169. * Json 转换为 Set<T> 若Json字符串为 null 或 empty 或 转换异常时,返回null
  170. */
  171. public <T> Set<T> toSet(String jsonStr, Class<T> clazz) {
  172. JavaType javaType = this.constructCollectionType(Set.class, clazz);
  173. return this.parseJson(jsonStr, javaType);
  174. }
  175. /**
  176. * Json to HashMap
  177. */
  178. public <T> Map<String, T> toMap(String jsonStr, Class<T> bean) {
  179. if (StringUtils.isEmpty(jsonStr)) {
  180. return null;
  181. }
  182. try {
  183. JavaType javaType = constructMapType(HashMap.class, String.class, bean);
  184. return mapper.readValue(jsonStr, javaType);
  185. } catch (IOException e) {
  186. LOG.error("parseJson error!" + e.getMessage(), e);
  187. return null;
  188. }
  189. }
  190. /**
  191. * 构造Array类型
  192. */
  193. public JavaType constructArrayType(Class<?> elementClass) {
  194. return mapper.getTypeFactory().constructArrayType(elementClass);
  195. }
  196. /**
  197. * 构造Collection类型
  198. */
  199. public JavaType constructCollectionType(Class<? extends Collection> collectionClass, Class<?> elementClass) {
  200. return mapper.getTypeFactory().constructCollectionType(collectionClass, elementClass);
  201. }
  202. /**
  203. * 构造Map类型
  204. */
  205. public JavaType constructMapType(Class<? extends Map> mapClass, Class<?> keyClass, Class<?> valueClass) {
  206. return mapper.getTypeFactory().constructMapType(mapClass, keyClass, valueClass);
  207. }
  208. /**
  209. * 当JSON里只含有Bean的部分属性時,更新一個已存在Bean,只覆盖該部分的属性
  210. */
  211. public void update(String jsonStr, Object object) {
  212. if (jsonStr == null) {
  213. return;
  214. }
  215. try {
  216. mapper.readerForUpdating(object).readValue(jsonStr);
  217. } catch (JsonProcessingException e) {
  218. LOG.error("updateJson error!" + e.getMessage(), e);
  219. } catch (IOException e) {
  220. LOG.error("updateJson error!" + e.getMessage(), e);
  221. }
  222. }
  223. /**
  224. * 輸出JSONP格式数据
  225. */
  226. public String toJsonP(String functionName, Object object) {
  227. if (object == null) {
  228. return null;
  229. }
  230. return toJson(new JSONPObject(functionName, object));
  231. }
  232. /**
  233. * 設定是否使用Enum的toString函数來读写Enum 为False時使用Enum的name()函数來读写Enum, 默认为False
  234. * 注意本函数一定要在Mapper創建後, 所有的读写動作之前調用
  235. */
  236. public void enableEnumUseToString() {
  237. mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
  238. mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
  239. }
  240. /**
  241. * 取出Mapper做进一步的设置或使用其他序列化API
  242. */
  243. public ObjectMapper getMapper() {
  244. return mapper;
  245. }
  246. /***
  247. * 把Json字符串转换成Node对象
  248. */
  249. public JsonNode getNode(String jsonStr) {
  250. if (jsonStr == null) {
  251. return null;
  252. }
  253. try {
  254. // mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS,
  255. // true);
  256. return mapper.readTree(jsonStr);
  257. } catch (IOException e) {
  258. LOG.error(e.getMessage(), e);
  259. return null;
  260. }
  261. }
  262. }