1
0

JacksonUtil.java 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. package com.kmall.admin.utils.jackson;
  2. import com.fasterxml.jackson.annotation.JsonFilter;
  3. import com.fasterxml.jackson.annotation.JsonInclude;
  4. import com.fasterxml.jackson.core.JsonGenerationException;
  5. import com.fasterxml.jackson.core.JsonGenerator;
  6. import com.fasterxml.jackson.core.JsonParseException;
  7. import com.fasterxml.jackson.core.JsonParser;
  8. import com.fasterxml.jackson.core.type.TypeReference;
  9. import com.fasterxml.jackson.databind.DeserializationFeature;
  10. import com.fasterxml.jackson.databind.JsonMappingException;
  11. import com.fasterxml.jackson.databind.ObjectMapper;
  12. import com.fasterxml.jackson.databind.SerializationFeature;
  13. import com.fasterxml.jackson.databind.module.SimpleModule;
  14. import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
  15. import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
  16. import org.slf4j.Logger;
  17. import org.slf4j.LoggerFactory;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.io.Reader;
  21. import java.io.StringWriter;
  22. import java.time.LocalDate;
  23. import java.time.LocalDateTime;
  24. import java.time.LocalTime;
  25. import java.time.format.DateTimeFormatter;
  26. import java.util.Date;
  27. import java.util.Locale;
  28. /**
  29. * @author Scott Chen
  30. * @version 1.0
  31. * 2017-09-18 18:42
  32. */
  33. public class JacksonUtil {
  34. private static final Logger logger = LoggerFactory.getLogger(JacksonUtil.class);
  35. private static ObjectMapper objectMapper;
  36. private static final String DYNC_INCLUDE = "DYNC_INCLUDE";//包含的标识
  37. private static final String DYNC_EXCLUDE = "DYNC_EXCLUDE";//过滤的标识
  38. @JsonFilter(DYNC_EXCLUDE)
  39. interface DynamicExclude{
  40. }
  41. @JsonFilter(DYNC_INCLUDE)
  42. interface DynamicInclude{
  43. }
  44. /**
  45. * 禁止调用无参构造
  46. *
  47. * @throws IllegalAccessException
  48. */
  49. private JacksonUtil() throws IllegalAccessException {
  50. throw new IllegalAccessException("Can't create an instance!");
  51. }
  52. /**
  53. * 懒惰单例模式得到ObjectMapper实例
  54. * 此对象为Jackson的核心
  55. */
  56. private static final ObjectMapper objectMapper() {
  57. if (objectMapper== null){
  58. objectMapper= new ObjectMapper();
  59. // 格式化国家环境指定
  60. objectMapper.setLocale(Locale.SIMPLIFIED_CHINESE);
  61. //序列化时,如果没有为类型找到访问者,则会抛出异常以将其指定为非可序列化类型; 如果禁用,它们将被序列化为空对象
  62. objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
  63. //反序列化时,遇到未知属性是否抛JsonMappingException异常.默认JsonMappingException
  64. objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  65. //设置null值不参与序列化(字段不被显示)
  66. objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
  67. //序列化Unicode编码非ASCII字符
  68. //objectMapper.registerModule(unicodeSerModule());
  69. }
  70. return objectMapper;
  71. }
  72. /**
  73. * ObjectMapper 实例
  74. * @return
  75. */
  76. public static ObjectMapper getObjectMapper() {
  77. return objectMapper();
  78. }
  79. /**
  80. * 创建Json处理器的静态方法
  81. * 用于序列化
  82. * @param content Json字符串
  83. * @return
  84. */
  85. private static JsonParser getParser(String content){
  86. try{
  87. return objectMapper().getFactory().createParser(content);
  88. }catch (IOException ioe){
  89. return null;
  90. }
  91. }
  92. /**
  93. * 创建Byte Json处理器的静态方法
  94. * 用于序列化
  95. * @param data byte array
  96. * @return
  97. */
  98. private static JsonParser getByteParser(byte[] data){
  99. try{
  100. return objectMapper().getFactory().createParser(data);
  101. }catch (IOException ioe){
  102. return null;
  103. }
  104. }
  105. /**
  106. * 创建Reader Json处理器的静态方法
  107. * 用于序列化
  108. * @param r Reader
  109. * @return
  110. */
  111. private static JsonParser getReaderParser(Reader r){
  112. try{
  113. return objectMapper().getFactory().createParser(r);
  114. }catch (IOException ioe){
  115. return null;
  116. }
  117. }
  118. /**
  119. * 创建InputStream Json处理器的静态方法
  120. * 用于序列化
  121. * @param in InputStream
  122. * @return
  123. */
  124. private static JsonParser getReaderParser(InputStream in){
  125. try{
  126. return objectMapper().getFactory().createParser(in);
  127. }catch (IOException ioe){
  128. return null;
  129. }
  130. }
  131. /**
  132. * 创建Json生成器的静态方法, 使用标准输出
  133. * 用于反序列化
  134. * @return
  135. */
  136. private static JsonGenerator getGenerator(StringWriter sw){
  137. try{
  138. return objectMapper().getFactory().createGenerator(sw);
  139. }catch (IOException e) {
  140. return null;
  141. }
  142. }
  143. /**
  144. * Json对象序列化
  145. */
  146. public static String toJson(Object obj){
  147. StringWriter sw= new StringWriter();
  148. JsonGenerator jsonGen= getGenerator(sw);
  149. if (jsonGen== null){
  150. try {
  151. sw.close();
  152. } catch (IOException e) {
  153. }
  154. return null;
  155. }
  156. try {
  157. //由于在getGenerator方法中指定了OutputStream为sw
  158. //因此调用writeObject会将数据输出到sw
  159. jsonGen.writeObject(obj);
  160. //由于采用流式输出 在输出完毕后务必清空缓冲区并关闭输出流
  161. jsonGen.flush();
  162. jsonGen.close();
  163. return sw.toString();
  164. } catch (JsonGenerationException jge) {
  165. logger.error("toJSON序列化失败, 异常类型【JsonGenerationException】,错误原因:{}", jge.getMessage());
  166. } catch (IOException ioe) {
  167. logger.error("toJSON序列化失败, 异常类型【IOException】, 错误原因:{}", ioe.getMessage());
  168. ioe.printStackTrace();
  169. }
  170. return null;
  171. }
  172. /**
  173. * 将Json Byte反序列化成对象
  174. *
  175. * @param data
  176. * @param clazz
  177. * @return
  178. */
  179. public static <T> T fromByteJson(byte[] data, Class<T> clazz) {
  180. try {
  181. JsonParser jp= getByteParser(data);
  182. return jp.readValueAs(clazz);
  183. } catch (JsonParseException e){
  184. logger.error(String.format("fromByteJson反序列化失败, 异常类型【JsonParseException】, 错误原因:{}", e.getMessage()));
  185. } catch (JsonMappingException e){
  186. logger.error(String.format("fromByteJson反序列化失败, 异常类型【JsonMappingException】, 错误原因:{}", e.getMessage()));
  187. } catch (IOException e){
  188. logger.error(String.format("fromByteJson反序列化失败, 异常类型【IOException】, 错误原因:{}", e.getMessage()));
  189. }
  190. return null;
  191. }
  192. /**
  193. * 将Json String反序列化成对象
  194. *
  195. * @param json
  196. * @param clazz
  197. * @return
  198. */
  199. public static <T> T fromStringJson(String json, Class<T> clazz) {
  200. try {
  201. JsonParser jp= getParser(json);
  202. return (T) jp.readValueAs(clazz);
  203. } catch (JsonParseException e) {
  204. logger.error(String.format("fromStringJson反序列化失败, 异常类型【JsonParseException】, 错误原因:{}", e.getMessage()));
  205. logger.error("decode(String, Class<T>)", e);
  206. } catch (JsonMappingException e) {
  207. logger.error(String.format("fromStringJson反序列化失败, 异常类型【JsonMappingException】, 错误原因:{}", e.getMessage()));
  208. logger.error("decode(String, Class<T>)", e);
  209. } catch (IOException e) {
  210. logger.error(String.format("fromStringJson反序列化失败, 异常类型【IOException】, 错误原因:{}", e.getMessage()));
  211. logger.error("decode(String, Class<T>)", e);
  212. }
  213. return null;
  214. }
  215. /**
  216. * 将Json Array或List反序列化为对象
  217. *
  218. * @param json
  219. * @return
  220. */
  221. public static <T> T fromListJson(String json, TypeReference<?> typeReference) {
  222. try {
  223. //写成List.class是不行的
  224. JsonParser jp= getParser(json);
  225. return (T) jp.readValueAs(typeReference);
  226. } catch (JsonParseException e) {
  227. logger.error(String.format("fromListJson反序列化失败, 异常类型【JsonParseException】, 错误原因:{}", e.getMessage()));
  228. logger.error("decode(String, Class<T>)", e);
  229. } catch (JsonMappingException e) {
  230. logger.error(String.format("fromListJson反序列化失败, 异常类型【JsonMappingException】, 错误原因:{}", e.getMessage()));
  231. logger.error("decode(String, Class<T>)", e);
  232. } catch (IOException e) {
  233. logger.error(String.format("fromListJson反序列化失败, 异常类型【IOException】, 错误原因:{}", e.getMessage()));
  234. logger.error("decode(String, Class<T>)", e);
  235. }
  236. return null;
  237. }
  238. }