解决Long类型web前端精度丢失问题

1 背景

后端编号采用分布式Id长度19位,如:1564586000854925325,如果直接返回前端Long类型会出现最后1位精度缺失问题,前端接收的数字为:1564586000854925320

2 原因

Java中Long的取值范围:

-9223372036854775808到9223372036854775807(即-2^64“ 到”2^64-1)

JavaScript中的Number取值范围:

-9007199254740992 到9007199254740991 (即-2^53 到2^53-1)

3 解决方法

将Long类型转成String

3.1 spring-boot程序方法1

@Configuration
public class MappingJackson2HttpMessageConverterConfig {

    @Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();

        ObjectMapper objectMapper = new ObjectMapper();
        // 反序列化忽略未知属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);

        // 全局转化Long类型为String,解决Jackson序列化时web精度确实问题
        SimpleModule simpleModule=new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);       

        converter.setObjectMapper(objectMapper);
        return converter;
    }
}

3.2 spring-boot程序方法2

@Configuration
public class JacksonConfig {

  /**
   * Jackson全局转化long类型为String,解决long类型缺失精度问题
   *
   * @return Jackson2ObjectMapperBuilderCustomizer 注入的对象
   */
  @Bean
  public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
    return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder
        .serializerByType(Long.class, ToStringSerializer.instance)
        .serializerByType(Long.TYPE, ToStringSerializer.instance);
  }
}

你可能感兴趣的:(springboot,前端,Long类型,精度丢失)