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

    }
}
相关推荐
还是大剑师兰特8 小时前
TypeScript 面试题及详细答案 100题 (91-100)-- 工程实践与框架集成
前端·javascript·typescript·1024程序员节
羊锦磊8 小时前
[ Redis ] SpringBoot集成使用Redis(补充)
java·数据库·spring boot·redis·spring·缓存·json
用户47949283569158 小时前
typeof null === 'object':JavaScript 最古老的 bug 为何 30 年无法修复?
前端·javascript·面试
__WanG9 小时前
如何编写标准StatefulWidget页面
前端·flutter
非凡ghost9 小时前
By Click Downloader(下载各种在线视频) 多语便携版
前端·javascript·后端
非凡ghost9 小时前
VisualBoyAdvance-M(GBA模拟器) 中文绿色版
前端·javascript·后端
非凡ghost9 小时前
K-Lite Mega/FULL Codec Pack(视频解码器)
前端·javascript·后端
LinXunFeng9 小时前
Flutter 多仓库本地 Monorepo 方案与体验优化
前端·flutter·架构
非凡ghost9 小时前
ProcessKO(查杀隐藏危险进程)多语便携版
前端·javascript·后端
摇滚侠9 小时前
Spring Boot3零基础教程,整合 SSM,笔记52
java·spring boot·笔记