【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;

    }
}
相关推荐
hashiqimiya38 分钟前
两个步骤,打包war,tomcat使用war包
java·服务器·前端
零度@1 小时前
Java中Map的多种用法
java·前端·python
yuanyxh2 小时前
静默打印程序实现
前端·react.js·electron
三十_A3 小时前
如何正确实现圆角渐变边框?为什么 border-radius 对 border-image 不生效?
前端·css·css3
小满zs3 小时前
Next.js第十三章(缓存组件)
前端
前端老宋Running3 小时前
“受控组件”的诅咒:为什么你需要 React Hook Form + Zod 来拯救你的键盘?
前端·javascript·react.js
风止何安啊3 小时前
拿捏 React 组件通讯:从父子到跨组件的「传功秘籍」
前端·react.js·面试
懒得不想起名字3 小时前
将flutter打成aar包嵌入到安卓
前端
Highcharts.js4 小时前
官方文档|Angular 框架集成 Highcharts Dashboards
前端·javascript·angular.js·highcharts·看板·使用文档·dashboards
韭菜炒大葱4 小时前
React 新手村通关指南:状态、组件与魔法 UI 🧙‍♂️
前端·javascript·react.js