最近项目中使用雪花ID作为主键,雪花ID是19位Long类型数字,数据返回到前端会出现精度丢失问题,数字已经超过了前端浏览器或JS的最大值。
序列化时将Long类型转成String类型
1、在启动类中加 @JsonComponent 注解
2、再在启动类中加上以下代码
@Beanpublic 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;}
在前端使用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
})
点关注不迷路,喜欢的朋友们关注支持一下 |
---|
给点继续写的动力,感谢!! |
上一篇:对JSP文件的理解
下一篇:天干地支(Java)