JsonMapper.java 9.2 KB

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