JacksonUtils.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. package com.emato.common.utils.oms;
  2. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  3. import com.fasterxml.jackson.annotation.JsonInclude;
  4. import com.fasterxml.jackson.annotation.PropertyAccessor;
  5. import com.fasterxml.jackson.core.JsonFactory;
  6. import com.fasterxml.jackson.core.JsonGenerator;
  7. import com.fasterxml.jackson.core.JsonParser;
  8. import com.fasterxml.jackson.core.JsonProcessingException;
  9. import com.fasterxml.jackson.core.type.TypeReference;
  10. import com.fasterxml.jackson.databind.DeserializationFeature;
  11. import com.fasterxml.jackson.databind.JavaType;
  12. import com.fasterxml.jackson.databind.ObjectMapper;
  13. import com.fasterxml.jackson.databind.SerializationFeature;
  14. import com.fasterxml.jackson.databind.module.SimpleModule;
  15. import org.slf4j.Logger;
  16. import org.slf4j.LoggerFactory;
  17. import java.io.IOException;
  18. import java.io.StringWriter;
  19. import java.time.LocalDate;
  20. import java.time.LocalDateTime;
  21. import java.time.LocalTime;
  22. import java.time.format.DateTimeFormatter;
  23. import java.util.Date;
  24. import java.util.Locale;
  25. import java.util.Map;
  26. /**
  27. * JacksonUtils 工具类
  28. * @author Scott Chen
  29. * @version 1.0
  30. * 2017-09-18 18:42
  31. */
  32. public class JacksonUtils {
  33. private static final Logger logger = LoggerFactory.getLogger(JacksonUtils.class);
  34. private static ObjectMapper objectMapper;
  35. private static final ThreadLocal<JacksonUtils> jacksonUtilThreadLocal = new ThreadLocal<>();
  36. private static final ThreadLocal<ObjectMapper> objectMapperThreadLocal = new ThreadLocal<>();
  37. /**
  38. * 禁止调用无参构造
  39. */
  40. private JacksonUtils() {}
  41. /**
  42. * JacksonUtils 工具类实例
  43. * @return
  44. */
  45. public static JacksonUtils instance() {
  46. JacksonUtils instance = jacksonUtilThreadLocal.get();
  47. if (instance == null) {
  48. instance = new JacksonUtils();
  49. jacksonUtilThreadLocal.set(instance);
  50. }
  51. return instance;
  52. }
  53. /**
  54. * ObjectMapper实例
  55. * @return
  56. */
  57. public static ObjectMapper objectMapper() {
  58. objectMapper = objectMapperThreadLocal.get();
  59. if (objectMapper== null){
  60. objectMapper= new ObjectMapper();
  61. // 格式化国家环境指定
  62. objectMapper.setLocale(Locale.SIMPLIFIED_CHINESE);
  63. // 设置可见性
  64. // PropertyAccessor: 属性访问器, IS_GETTER, getter-like methods that are named "isXxx" (instead of "getXxx" for getters) and return boolean value
  65. // Visibility: 可见性, PUBLIC_ONLY, 仅 public 修饰符 允许
  66. objectMapper.setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.PUBLIC_ONLY);
  67. // 序列化时, 当序列化数据中如果没有对应类型的数据时发生什么, 设置为true(默认),则会抛出异常,设置为false, 则会序列化为空对象
  68. objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
  69. // 反序列化时, 数据有值,但类型没有对应属性, 是否抛JsonMappingException异常, 默认为true, 抛出JsonMappingException
  70. objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
  71. // 反序列化时, 允许空值("")是否转换为空对象`null` , 默认false, 不允许
  72. objectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
  73. // 反序列化时, 多态的类型时会发生什么的, true(默认),抛出异常; 如果为false, 则使用null值
  74. //objectMapper.disable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE);
  75. // 反序列化时, 确定遇到Object Id引用时会发生什么的, 默认true,抛出异常,false, 则不会进行进一步处理
  76. //objectMapper.disable(DeserializationFeature.FAIL_ON_UNRESOLVED_OBJECT_IDS);
  77. // 反序列化时, 属性注释不存在, 但关联的类型id可用的处理, 默认true, 抛出JsonMappingException
  78. objectMapper.disable(DeserializationFeature.FAIL_ON_MISSING_EXTERNAL_TYPE_ID_PROPERTY);
  79. // 序列化和反序列化时, 避免转义字符抛出异常情况
  80. objectMapper.enable(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS) ;
  81. // 序列化和反序列化时, 允许没有引号的字段名(非标准)
  82. objectMapper.enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);
  83. //设置null值不参与序列化(字段不被显示)
  84. objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
  85. // //注册序列化LocalDateTime模块
  86. // objectMapper.registerModule(localDateTimeSerializer());
  87. // //注册反序列化LocalDateTime模块
  88. // objectMapper.registerModule(localDateTimeDeserializer());
  89. // //注册序列化Date模块
  90. // objectMapper.registerModule(dateTimeSerializer());
  91. // //注册反序列化Date模块
  92. // objectMapper.registerModule(dateTimeDeserializer());
  93. //序列化Unicode编码非ASCII字符
  94. //objectMapper.registerModule(unicodeSerModule());
  95. objectMapperThreadLocal.set(objectMapper);
  96. }
  97. return objectMapper;
  98. }
  99. public ObjectMapper getObjectMapper() {
  100. return objectMapper();
  101. }
  102. /**
  103. * 序列化Date
  104. * 自定义
  105. * @return
  106. */
  107. // private static SimpleModule dateTimeSerializer(){
  108. // SimpleModule module = new SimpleModule();
  109. // module.addSerializer(Date.class, new DateTimeSerializer());
  110. // return module;
  111. // }
  112. /**
  113. * 反列化Date
  114. * 自定义
  115. * @return
  116. */
  117. // private static SimpleModule dateTimeDeserializer(){
  118. // SimpleModule module = new SimpleModule();
  119. // module.addDeserializer(Date.class, new DateTimeDeserializer());
  120. // return module;
  121. // }
  122. /**
  123. * 序列化LocalDateTime时间
  124. * 使用 <code>jackson-datatype-jsr310</code>
  125. * @return
  126. */
  127. // private static SimpleModule localDateTimeSerializer() {
  128. // SimpleModule module = new SimpleModule();
  129. // module.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DateConstant.DATE_MONTH_DAY, Locale.SIMPLIFIED_CHINESE)));
  130. // module.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DateConstant.TIME_SECOND, Locale.SIMPLIFIED_CHINESE)));
  131. // module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DateConstant.DATE_TIME_SECOND, Locale.SIMPLIFIED_CHINESE)));
  132. // return module;
  133. // }
  134. /**
  135. * 反序列化LocalDateTime时间
  136. * 使用 <code>jackson-datatype-jsr310</code>
  137. * @return
  138. */
  139. // private static SimpleModule localDateTimeDeserializer() {
  140. // SimpleModule module = new SimpleModule();
  141. // module.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DateConstant.DATE_MONTH_DAY, Locale.SIMPLIFIED_CHINESE)));
  142. // module.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DateConstant.TIME_SECOND, Locale.SIMPLIFIED_CHINESE)));
  143. // module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DateConstant.DATE_TIME_SECOND, Locale.SIMPLIFIED_CHINESE)));
  144. // return module;
  145. // }
  146. /**
  147. * 序列化Unicode编码非ASCII字符
  148. */
  149. private static SimpleModule unicodeSerModule() {
  150. SimpleModule unicodeSerModule = new SimpleModule();
  151. unicodeSerModule.addSerializer(String.class, new JacksonStringUnicodeSerializer());
  152. return unicodeSerModule;
  153. }
  154. private static JsonFactory getJsonFactory() {
  155. return objectMapper().getFactory();
  156. }
  157. // -------------------- to json --------------------
  158. /**
  159. * bject对象序列化为Json字符串
  160. * @param obj
  161. * @param <T>
  162. * @return
  163. */
  164. public static <T> String toJsonStr(T obj) {
  165. return toJsonStr(obj, false);
  166. }
  167. /**
  168. * Object对象序列化为Json字符串
  169. *
  170. * @param obj
  171. * @param isPretty 是否美化
  172. * @param <T>
  173. * @return
  174. */
  175. public static <T> String toJsonStr(T obj, boolean isPretty) {
  176. if (obj == null) {
  177. return null;
  178. }
  179. if (obj instanceof String) {
  180. return (String) obj;
  181. }
  182. StringWriter sw = new StringWriter();
  183. JsonGenerator generator;
  184. try {
  185. generator = objectMapper().getFactory().createGenerator(sw);
  186. if (generator == null) {
  187. sw.close();
  188. return null;
  189. }
  190. if (isPretty) {
  191. generator.useDefaultPrettyPrinter().writeObject(obj);
  192. } else {
  193. generator.writeObject(obj);
  194. }
  195. generator.close();
  196. return sw.toString();
  197. } catch (IOException ioe) {
  198. logger.error("toJSON序列化失败, 异常类型【IOException】, 错误原因:{}", ioe.getMessage());
  199. ioe.printStackTrace();
  200. return null;
  201. }
  202. }
  203. /**
  204. * Object对象序列化为Json字符串
  205. *
  206. * @param obj
  207. * @param isPretty
  208. * @param <T>
  209. * @return
  210. */
  211. public static <T> String toJsonStrWithObjectMapper(T obj, boolean isPretty) {
  212. if (obj == null){
  213. return null;
  214. }
  215. if (obj instanceof String) {
  216. return (String) obj;
  217. }
  218. String result;
  219. try {
  220. if (isPretty) {
  221. result = objectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(obj);
  222. } else {
  223. result = objectMapper().writeValueAsString(obj);
  224. }
  225. return result;
  226. } catch (JsonProcessingException jpe) {
  227. logger.error("toJSON序列化失败, 异常类型【JsonProcessingException】, 错误原因:{}", jpe.getMessage());
  228. jpe.printStackTrace();
  229. return null;
  230. }
  231. }
  232. // -------------------- from json --------------------
  233. /**
  234. * 将Json Byte反序列化成对象
  235. *
  236. * @param data
  237. * @param clazz
  238. * @return
  239. */
  240. public static <T> T parseJson(byte[] data, Class<T> clazz) {
  241. try {
  242. JsonParser parser = objectMapper().getFactory().createParser(data);
  243. return parser.readValueAs(clazz);
  244. } catch (IOException e){
  245. logger.error(String.format("fromJson反序列化失败, 异常类型【IOException】, 错误原因:{}", e.getMessage()));
  246. }
  247. return null;
  248. }
  249. /**
  250. * 将Json String反序列化成对象
  251. *
  252. * @param json
  253. * @param clazz
  254. * @return
  255. */
  256. public static <T> T parseJson(String json, Class<T> clazz) {
  257. try {
  258. JsonParser parser = objectMapper().getFactory().createParser(json);
  259. return clazz.equals(String.class) ? (T) json : parser.readValueAs(clazz);
  260. } catch (IOException e) {
  261. logger.error(String.format("fromJson反序列化失败, 异常类型【IOException】, 错误原因:{}", e.getMessage()));
  262. logger.error("decode(String, Class<T>)", e);
  263. }
  264. return null;
  265. }
  266. /**
  267. * 将Json Array或List反序列化为对象
  268. *
  269. * @param json
  270. * @param typeReference 被转对象引用类型
  271. * @param <T>
  272. * @return
  273. */
  274. public static <T> T parseJson(String json, TypeReference<T> typeReference) {
  275. try {
  276. JsonParser parser = objectMapper().getFactory().createParser(json);
  277. //写成List.class是不行的
  278. return (T) (typeReference.getType().equals(String.class) ? json : parser.readValueAs(typeReference));
  279. }catch (IOException e) {
  280. logger.error(String.format("fromJson反序列化失败, 异常类型【IOException】, 错误原因:{}", e.getMessage()));
  281. logger.error("decode(String, Class<T>)", e);
  282. }
  283. return null;
  284. }
  285. /**
  286. * string转object 用于转为集合对象
  287. * @param json json字符串
  288. * @param collectionClass 被转集合class
  289. * @param elementClasses 被转集合中对象类型class
  290. * @param <T>
  291. * @return
  292. */
  293. public static <T> T parseJson(String json, Class<?> collectionClass, Class<?>... elementClasses){
  294. JavaType javaType = objectMapper()
  295. .getTypeFactory()
  296. .constructParametricType(collectionClass, elementClasses);
  297. try {
  298. return objectMapper().readValue(json, javaType);
  299. } catch (IOException e) {
  300. logger.error("Parse String to Object error.");
  301. e.printStackTrace();
  302. return null;
  303. }
  304. }
  305. // -------------------- map to bean --------------------
  306. /**
  307. * map 转 bean
  308. * @param map
  309. * @param clazz
  310. * @param <T>
  311. * @return
  312. */
  313. public static <T> T mapToBean(Map map, Class<T> clazz) {
  314. return objectMapper().convertValue(map, clazz);
  315. }
  316. }