• Jackson 工具类
      • 对象转字符串
      • 字符串转对象
      • 字符串转未知对象 (TypeReference实现)
      • 字符串转集合类 ```java

    /**

    • jackson 序列化工具类 */ @Slf4j public class JacksonUtil { private JacksonUtil() { }

      private static final ObjectMapper objectMapper;

      static {

      1. objectMapper = new ObjectMapper();
      2. // 对象的所有属性都保留
      3. objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
      4. // 取消默认转换为timestamp形式
      5. objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
      6. // 忽略空 bean 转 json 的错误
      7. objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
      8. // 所有的日期格式都统一为 yyyy-MM-dd HH:mm:ss
      9. objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
      10. // 忽略在 json 字符串中存在,对应 bean 不存在字段的情况,避免错误
      11. objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

      }

      /**

      • 对象转字符串

        *
      • @param obj 对象
      • @param 对象类型
      • @return {@link String} 序列化后的字符串 */ public static String obj2String(T obj) { if (Objects.isNull(obj)) {

        1. return null;

        } try {

        1. return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);

        } catch (Exception e) {

        1. log.warn("Parse object to String error: {}", e.getLocalizedMessage(), e);
        2. return null;

        } }

        /**

      • 对象转字符串, 友好展示

        *
      • @param obj 对象
      • @param 对象类型
      • @return {@link String} 序列化后的字符串 */ public static String obj2StringPretty(T obj) { if (Objects.isNull(obj)) {

        1. return null;

        } try {

        1. return obj instanceof String ? (String) obj : objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);

        } catch (Exception e) {

        1. log.warn("Parse object to String error: {}", e.getLocalizedMessage(), e);
        2. return null;

        } }

        /**

      • 字符串转对象

        *
      • @param str json 字符串
      • @param tClass 要转换的对象 class 对象
      • @param 要转换的对象类型
      • @return 转换后的对象 */ public static T string2Obj(String str, Class tClass) { if (Objects.isNull(str) || “”.equals(str) || Objects.isNull(tClass)) {

        1. return null;

        } try {

        1. return tClass == String.class ? (T) str : objectMapper.readValue(str, tClass);

        } catch (Exception e) {

        1. log.warn("Parse String to obj error: {}", e.getLocalizedMessage(), e);
        2. return null;

        } }

        /**

      • 根据 TypeReference {@link TypeReference} 将字符串转为对象

        *
      • @param str json字符串
      • @param typeReference 引用类型
      • @param 对象类型
      • @return 转换后的对象 */ public static T string2Obj(String str, TypeReference typeReference) { if (Objects.isNull(str) || “”.equals(str) || Objects.isNull(typeReference)) {

        1. return null;

        } try {

        1. return typeReference.getType().equals(String.class) ? (T) str : objectMapper.readValue(str, typeReference);

        } catch (Exception e) {

        1. log.warn("Parse String to obj error: {}", e.getLocalizedMessage(), e);
        2. return null;

        } }

        /**

      • 将字符串转换为集合类对象

        *
      • @param str json 字符串
      • @param collectionClass 集合类 class
      • @param itemClasses 元素 class
      • @param 对象类型
      • @return 转换后的对象 */ public static T string2Obj(String str, Class<?> collectionClass, Class<?>… itemClasses) { JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass, itemClasses); try {

        1. return objectMapper.readValue(str, javaType);

        } catch (Exception e) {

        1. log.warn("Parse String to obj error: {}", e.getLocalizedMessage(), e);
        2. return null;

        } }

        /**

      • 测试类 */ @Getter @Setter @AllArgsConstructor @NoArgsConstructor @ToString private static class User1 { private Integer id;

        private String name;

        @JsonDeserialize(using = LocalDateTimeDeserializer.class) @JsonSerialize(using = LocalDateTimeSerializer.class) private LocalDateTime localDateTime;

        private Date date;

    1. }
    2. /**
    3. * 测试
    4. */
    5. public static void main(String[] args) {
    6. User1 user1 = new User1();
    7. user1.setId(100);
    8. user1.setLocalDateTime(LocalDateTime.now());
    9. user1.setDate(new Date());
    10. // 对象转字符串
    11. String str = JacksonUtil.obj2String(user1);
    12. System.out.println(str);
    13. // 对象转字符串 友好展示
    14. str = JacksonUtil.obj2StringPretty(user1);
    15. System.out.println(str);
    16. // 字符串转对象
    17. System.out.println(JacksonUtil.string2Obj(str, User1.class));
    18. List<User1> user1List = new ArrayList<>();
    19. user1List.add(new User1(1, "a", LocalDateTime.now(), new Date()));
    20. user1List.add(new User1(2, "b", LocalDateTime.now(), new Date()));
    21. user1List.add(new User1(3, "c", LocalDateTime.now(), new Date()));
    22. System.out.println("=============================================================");
    23. str = JacksonUtil.obj2String(user1List);
    24. // 字符串转未知类型
    25. System.out.println(JacksonUtil.string2Obj(str, new TypeReference<List<User1>>() {
    26. }));
    27. // 字符串转集合类型
    28. List<User1> user1List2 = JacksonUtil.string2Obj(str, List.class, User1.class);
    29. System.out.println(user1List2);
    30. }

    }

    ```