一、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)
}]
})