JacksonUtils.java 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package com.uas.demo.utils;
  2. import com.fasterxml.jackson.core.JsonProcessingException;
  3. import com.fasterxml.jackson.databind.JavaType;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import java.io.IOException;
  6. import java.util.ArrayList;
  7. import java.util.Collections;
  8. import java.util.List;
  9. /**
  10. * JSON 工具类
  11. *
  12. * history:
  13. * Created by huxz on 2017-3-1 10:16:03
  14. */
  15. public final class JacksonUtils {
  16. private static ObjectMapper objectMapper;
  17. /**
  18. * 把JSON文本parse为JavaBean
  19. */
  20. public static <T> T fromJson(String text, Class<T> clazz) {
  21. if (objectMapper == null) {
  22. objectMapper = new ObjectMapper();
  23. }
  24. try {
  25. return objectMapper.readValue(text, clazz);
  26. } catch (IOException e) {
  27. e.printStackTrace();
  28. }
  29. return null;
  30. }
  31. /**
  32. * 把JSON文本parse成JavaBean集合
  33. */
  34. public static <T> List<T> fromJsonArray(String text, Class<T> clazz) {
  35. if (objectMapper == null) {
  36. objectMapper = new ObjectMapper();
  37. }
  38. JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, clazz);
  39. try {
  40. return objectMapper.readValue(text, javaType);
  41. } catch (IOException e) {
  42. e.printStackTrace();
  43. }
  44. return Collections.emptyList();
  45. }
  46. /**
  47. * 将JavaBean序列化为JSON文本
  48. */
  49. public static String toJson(Object object) {
  50. if (objectMapper == null) {
  51. objectMapper = new ObjectMapper();
  52. }
  53. try {
  54. return objectMapper.writeValueAsString(object);
  55. } catch (JsonProcessingException e) {
  56. e.printStackTrace();
  57. }
  58. return null;
  59. }
  60. }