Long类型精度丢失
最近项目中使用雪花ID作为主键,雪花ID是19位Long类型数字,数据返回到前端会出现精度丢失问题,数字已经超过了前端浏览器或JS的最大值。
Java后端数据模型
返回到浏览器后的数据模型,前后数据不一致
解决方式一:后端处理
序列化时将Long类型转成String类型
1、在启动类中加 @JsonComponent 注解
2、再在启动类中加上以下代码
@Bean
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
//忽略value为null 时 key的输出
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
/**
* 序列换成json时,将所有的long变成string
* 因为js中得数字类型不能包含所有的java long值
*/
SimpleModule module = new SimpleModule();
module.addSerializer(Long.class, ToStringSerializer.instance);
module.addSerializer(Long.TYPE, ToStringSerializer.instance);
objectMapper.registerModule(module);
return objectMapper;
}
方式二 前端处理(Vue)
在前端使用JSONbig将大数字做安全处理
1、在package.json中引入JSONbig, “json-bigint”: “^1.0.0” ,执行npm install命令
2、在requesst.js中创建axios实例时增加代码处理,(重点)导入JSONbig和添加transformResponse属性,相当于拦截器,请求相应后处理先处理一下。
//导入JSONbig
import JSONbig from 'json-bigint'
// 在创建axios实例中增加transformResponse属性
const service = axios.create({
// axios中请求配置有baseURL选项,表示请求URL公共部分
baseURL: process.env.VUE_APP_BASE_API,
transformResponse: [function(data) {
try {
// 作用1:把json字符串转为js对象
// 作用2:把里面的大数字做安全处理
return JSONbig.parse(data)
} catch (e) {
return data
}
}],
// 超时
timeout: 10000
})
求关注、求点赞~~~
点关注不迷路,喜欢的朋友们关注支持一下 |
---|
给点继续写的动力,感谢!! |