SpringBoot中使用Jackson导致Long型数据精度丢失问题、处理jdk8日期类型转换

spring boot默认使用了jackson 处理请求映射,下面通过三种方案配置,对Long类型、jdk8日期类型的自定义转换处理

方案一:注解方式:

@JsonSerialize(using=ToStringSerializer.class)  
private Long bankcardHash;

方案二:自定义ObjectMapper (推荐)

/**
* 配置spring boot内嵌的Jackson序列化与反序列化类型映射
*
* -日期配置:
*      map.put(LocalDateTime.class, localDateTimeSerializer());
*      Spring Boot 提供了 spring.jackson.date-format配置可以让我们进行日期格式化,
*      但它只能格式化 java.util.Date。
* 	  定义一个配置类,在配置类注入Bean 实现日期全局格式化,同时还兼顾了 Date 和 LocalDateTime 并存。
*      需要配置
*      spring:
*        jackson:
*          date-format: yyyy-MM-dd HH:mm:ss
*          time-zone: GMT+8
*
*  -Long类型转为字符串:
*      map.put(Long.class, ToStringSerializer.instance);
*      解决Long类型数据返回到前端精度丢失问题
*/
@Configuration
public class JacksonSerializerConfig {
 @Value("${spring.jackson.date-format}")
 private String pattern;

 @Bean
 public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
     Map<Class<?>, JsonSerializer<?>> map = new HashMap<>();
     map.put(LocalDateTime.class, localDateTimeSerializer());
     map.put(Long.class, ToStringSerializer.instance);
     return builder -> builder.serializersByType(map);
 }

 @Bean
 public LocalDateTimeSerializer localDateTimeSerializer() {
     return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
 }
}

对于日期字符串的反序列化,需要加上注解:

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime updateTime;

方案三:配置参数

  jackson:
    generator:
      write_numbers_as_strings: true

该方式会强制将所有数字全部转成字符串输出,这种方式的优点是使用方便,不需要调整代码;缺点是颗粒度太大,所有的数字都被转成字符串输出了,包括按照timestamp格式输出的时间也是如此。

参考 http://orchidflower.oschina.io/2018/06/22/Handling-Bigint-using-Jackson-in-Springboot/

你可能感兴趣的:(spring)