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 @   zFlame_5020  阅读(1070)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示