【BUG】SpringBoot项目Long类型数据返回前端精度丢失问题

问题描述

后端再给前端返回数据,使用Long类型的时候存在精度丢失问题。

原因分析:

分布式项目中广泛使用雪花算法生成ID作为数据库表的主键,Long类型的雪花ID有19位,而前端接收Long类型用的是number类型,但是number类型的精度只有16位。这就导致雪花ID传到前端会出现精度丢失。


解决方案:

通过Jackson序列化转String

java 复制代码
@Configuration
public class SerializerConfig {
    /**
     * Long类型前端精度丢失问题,序列化时转String
     * @param mapperBuilder
     * @return
     */
    @Bean
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder mapperBuilder) {
        ObjectMapper build = mapperBuilder.createXmlMapper(false).build();
        build.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        SimpleModule module = new SimpleModule();
        module.addSerializer(Long.class, ToStringSerializer.instance);
        module.addSerializer(Long.TYPE, ToStringSerializer.instance);
        build.registerModule(module);
        return build;

    }
}
相关推荐
风度前端30 分钟前
用了都说好的 uniapp 路由框架
前端
冴羽31 分钟前
2026 年 Web 前端开发的 8 个趋势!
前端·javascript·vue.js
码银39 分钟前
ruoyi的前端(vue)新增的时候给字典设置默认值 但不能正常
前端
BD_Marathon1 小时前
配置文件分类
spring boot
M***Z2101 小时前
springboot中配置logback-spring.xml
spring boot·spring·logback
凌览1 小时前
别再死磕 Nginx!http-proxy-middleware 低配置起飞
前端·后端
f***28142 小时前
Springboot中使用Elasticsearch(部署+使用+讲解 最完整)
spring boot·elasticsearch·jenkins
EndingCoder2 小时前
类的继承和多态
linux·运维·前端·javascript·ubuntu·typescript
用户47949283569152 小时前
React 终于出手了:彻底终结 useEffect 的"闭包陷阱"
前端·javascript·react.js
程序员猫哥2 小时前
前端开发,一句话生成网站
前端