Long类型精度丢失问题解决方案

问题描述:

我们在查询Long类型的id数据时,返回客户端,浏览器会将json格式的字符串转化为js对象使用,Java数值类型数据对应js中的数据类型是number,因为Long类型的数字超过了js的数字处理范围,所以会出现精度丢失的问题。
image

解决方案:

让Long类型的值返回给客户端的时候,以字符串形式返回即可,这样客户端收到数据之后就会转化为js的字符串对象,就不会出现精度丢失的问题。因为我们使用SpringBoot进行项目开发, 在返回数据的使用SpringBoot会自动使用Jackson将我们返回的数据转化为JSON字符串返回给客户端, 所以只需要通过配置的方式告诉框架对应Long类型的值改如何转化即可。

image

在通用类common模块中创建jackson配置类,定义jackson序列化配置

点击查看代码
public class JacksonConfig {

    @Bean
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();

        // 将Long类型序列化成String类型 防止Long类型造成前端精度丢失
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);

        return objectMapper;
    }
}
在需要这个配置的微服务中,导入这个配置即可
点击查看代码
@Configuration
@Import({SwaggerConfiguration.class, ExceptionCatch.class, JacksonConfig.class})
public class InitConfig {
}
posted @ 2023-07-13 20:58  zFlame_5020  阅读(1164)  评论(0)    收藏  举报