JacksonUtil.java 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. package com.lote.wms.common.utils;
  2. import com.fasterxml.jackson.annotation.JsonInclude;
  3. import com.fasterxml.jackson.core.JsonGenerationException;
  4. import com.fasterxml.jackson.core.JsonGenerator;
  5. import com.fasterxml.jackson.core.JsonParseException;
  6. import com.fasterxml.jackson.core.JsonParser;
  7. import com.fasterxml.jackson.databind.*;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. import java.io.IOException;
  11. import java.io.StringWriter;
  12. import java.util.List;
  13. import java.util.Map;
  14. /**
  15. * @author Scott Chen
  16. * @version 1.0
  17. * 2017-09-18 18:42
  18. */
  19. public class JacksonUtil {
  20. private static final Logger logger = LoggerFactory.getLogger(JacksonUtil.class);
  21. private static ObjectMapper objectMapper;
  22. private static final ThreadLocal<ObjectMapper> objectMapperThreadLocal = new ThreadLocal<>();
  23. /**
  24. * 禁止调用无参构造
  25. *
  26. * @throws IllegalAccessException
  27. */
  28. private JacksonUtil() throws IllegalAccessException {
  29. throw new IllegalAccessException("Can't create an instance!");
  30. }
  31. public static ObjectMapper newObjectMapper() {
  32. objectMapper = objectMapperThreadLocal.get();
  33. if (objectMapper == null) {
  34. objectMapper = getObjectMapper();
  35. objectMapperThreadLocal.set(objectMapper);
  36. }
  37. return objectMapper;
  38. }
  39. /**
  40. * 懒惰单例模式得到ObjectMapper实例
  41. * 此对象为Jackson的核心
  42. */
  43. private static final ObjectMapper getObjectMapper() {
  44. if (objectMapper== null){
  45. objectMapper= new ObjectMapper();
  46. //序列化时,如果没有为类型找到访问者,则会抛出异常以将其指定为非可序列化类型; 如果禁用,它们将被序列化为空对象
  47. objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
  48. //反序列化时,遇到未知属性是否抛JsonMappingException异常.默认JsonMappingException
  49. objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  50. //设置null值不参与序列化(字段不被显示)
  51. objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
  52. }
  53. return objectMapper;
  54. }
  55. //-------------------- 序列化 --------------------
  56. /**
  57. * 创建JSON生成器
  58. * 序列化 writing JSON content
  59. * @return
  60. */
  61. private static JsonGenerator getGenerator(StringWriter sw){
  62. try{
  63. return getObjectMapper().getFactory().createGenerator(sw);
  64. }catch (IOException e) {
  65. return null;
  66. }
  67. }
  68. /**
  69. * 创建JSON处理器
  70. * 反序列化 reading JSON content
  71. * @param content JSON字符串
  72. * @return
  73. */
  74. private static JsonParser getParser(String content){
  75. try{
  76. return getObjectMapper().getFactory().createParser(content);
  77. }catch (IOException ioe){
  78. return null;
  79. }
  80. }
  81. /**
  82. * 对象序列化
  83. */
  84. public static String toJSON(Object obj){
  85. StringWriter sw= new StringWriter();
  86. JsonGenerator jsonGen= getGenerator(sw);
  87. if (jsonGen== null){
  88. try {
  89. sw.close();
  90. } catch (IOException e) {
  91. }
  92. return null;
  93. }
  94. try {
  95. //由于在getGenerator方法中指定了OutputStream为sw
  96. //因此调用writeObject会将数据输出到sw
  97. jsonGen.writeObject(obj);
  98. //由于采用流式输出 在输出完毕后务必清空缓冲区并关闭输出流
  99. jsonGen.flush();
  100. jsonGen.close();
  101. return sw.toString();
  102. } catch (JsonGenerationException jge) {
  103. logger.error("toJSON序列化失败, 异常类型【JsonGenerationException】,错误原因:%s", jge.getMessage());
  104. } catch (IOException ioe) {
  105. logger.error("toJSON序列化失败, 异常类型【IOException】, 错误原因:%s", ioe.getMessage());
  106. }
  107. return null;
  108. }
  109. /**
  110. * JSON反序列化
  111. */
  112. public static <T> T fromJSON(String json, Class<T> clazz) {
  113. try {
  114. JsonParser jp= getParser(json);
  115. return jp.readValueAs(clazz);
  116. } catch (JsonParseException jpe){
  117. logger.error(String.format("fromJSON反序列化失败, 异常类型【JsonParseException】, 错误原因:%s", jpe.getMessage()));
  118. } catch (JsonMappingException jme){
  119. logger.error(String.format("fromJSON反序列化失败, 异常类型【JsonMappingException】, 错误原因:%s", jme.getMessage()));
  120. } catch (IOException ioe){
  121. logger.error(String.format("fromJSON反序列化失败, 异常类型【IOException】, 错误原因:%s", ioe.getMessage()));
  122. }
  123. return null;
  124. }
  125. /**
  126. * JSON反序列化为List
  127. *
  128. * @param json
  129. * @param collectionClass
  130. * @param elementClass
  131. * @return
  132. * @throws JsonParseException
  133. * @throws JsonMappingException
  134. * @throws IOException
  135. */
  136. public static <T> List<T> toList(String json, Class<? extends List> collectionClass, Class<T> elementClass) {
  137. JavaType javaType = getObjectMapper().getTypeFactory().constructCollectionType(collectionClass, elementClass);
  138. try{
  139. return getObjectMapper().readValue(json, javaType);
  140. } catch (JsonParseException jpe){
  141. logger.error(String.format("toList反序列化失败, 异常类型【JsonParseException】, 错误原因:%s", jpe.getMessage()));
  142. } catch (JsonMappingException jme){
  143. logger.error(String.format("toList反序列化失败, 异常类型【JsonMappingException】, 错误原因:%s", jme.getMessage()));
  144. } catch (IOException ioe){
  145. logger.error(String.format("toList反序列化失败, 异常类型【IOException】, 错误原因:%s", ioe.getMessage()));
  146. }
  147. return null;
  148. }
  149. /**
  150. * JSON反序列化为Map
  151. *
  152. * @param json
  153. * @param mapClass
  154. * @param keyClass
  155. * @param valueClass
  156. * @return
  157. * @throws JsonParseException
  158. * @throws JsonMappingException
  159. * @throws IOException
  160. */
  161. public static <K, V> Map<K, V> toMap(String json, Class<? extends Map> mapClass, Class<K> keyClass,
  162. Class<V> valueClass) throws JsonParseException, JsonMappingException, IOException {
  163. JavaType javaType = getObjectMapper().getTypeFactory().constructMapType(mapClass, keyClass, valueClass);
  164. try{
  165. return getObjectMapper().readValue(json, javaType);
  166. }catch (JsonParseException jpe){
  167. logger.error(String.format("toMap反序列化失败, 异常类型【JsonParseException】, 错误原因:%s", jpe.getMessage()));
  168. } catch (JsonMappingException jme){
  169. logger.error(String.format("toMap反序列化失败, 异常类型【JsonMappingException】, 错误原因:%s", jme.getMessage()));
  170. } catch (IOException ioe){
  171. logger.error(String.format("toMap反序列化失败, 异常类型【IOException】, 错误原因:%s", ioe.getMessage()));
  172. }
  173. return null;
  174. }
  175. }