springboot2.x 解决Long类型的ID 精度丢失问题

一、Java 后端处理

JavaScript 无法处理 Java 的长整型 Long 导致精度丢失,具体表现为主键最后两位永远为 0,解决思路: Long 转为 String 返回

方式1 : 通过注解方式

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SysRoles implements Serializable {

    // 注解处理
    @JsonSerialize(using=ToStringSerializer.class)
    private Long id;

}

 

方式2: 全局设置 ,改写配置放在容器中。

    @Bean
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        SimpleModule module = new SimpleModule();
        module.addSerializer(Long.class, ToStringSerializer.instance);
        module.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(module);
        return objectMapper;
    }

 

二、前端JS处理

  • 安装 json-bigint 插件
AppledeMacBook-Pro:~ apple$ npm install json-bigint
  • 对请求进行拦截处理, 这里以axiso为例
import axios from 'axios'
import store from '@/store'
import JSONbig from 'json-bigint'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 30 * 1000,
  // 在自动解析 JSON 数据之前的 data,处理 Long 类型精度丢失问题
  transformResponse: [function(data) {
    return JSONbig.parse(data)
  }]
})

 

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值