如何处理Long类型精度丢失问题?

一、现象与分析

1.1. 现象

前后端交互,当后端传一些值给前端的时候,如果是long类型,有可能会出现数字太大而前端接收不了(java中的long大于js的number)而导致数据不一致,精度会丢失。

1.2. 分析

 1 <!DOCTYPE html>
 2 <html >
 3 <head>
 4     <title>test</title>
 5      <script>
 6         alert(1460543153605050369);
 7     </script>
 8 </head>
 9 <body>
10 <h2>欢迎使用!!</h2>
11 <div><a href="http://www.baidu.com" th:href="${info}">百度一下</a></div>
12 </body>
13 </html>
验证

例如:后端Long类型,前端number类型,它们的精度不一样,导致精度丢失现象
库中存的值:1460543153605050369
后端取的值:1460543153605050369
前端得到值:1460543153605050400

二、解决方案(后端处理)

    将Long类型转成String,再传给前端

2.1. 方法一单个注解
@JsonSerialize(using= ToStringSerializer.class)
private Long id;
单个注解

2.2. 方法二统一配置

 1 package com.jiawa.wiki.config;
 2 
 3 import com.fasterxml.jackson.databind.ObjectMapper;
 4 import com.fasterxml.jackson.databind.module.SimpleModule;
 5 import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
 6 import org.springframework.context.annotation.Bean;
 7 import org.springframework.context.annotation.Configuration;
 8 import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
 9 
10 /**
11  * 统一注解,解决前后端交互Long类型精度丢失的问题
12  */
13 @Configuration
14 public class JacksonConfig {
15 
16     @Bean
17     public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
18         ObjectMapper objectMapper = builder.createXmlMapper(false).build();
19         //全局配置序列化返回json处理
20         SimpleModule simpleModule = new SimpleModule();
21         //json Long ==>String
22         simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
23         objectMapper.registerModule(simpleModule);
24         return objectMapper;
25     }
26 }
统一配置
三、解决方案(前端处理)

前端一般都是用axios进行数据请求,我们通过引入json-bigint来解决

yarn add json-bigint
//或
npm install json-bigint

在封装的请求工具类中添加如下代码即可。

1 axios.defaults.transformResponse = [
2   function (data) {
3     const json = JSONBIG({
4       storeAsString: true
5     })
6     const res = json.parse(data)
7     return res
8   }
9 ]
在封装的请求工具类中添加

 

 

转自:
https://blog.csdn.net/weixin_40816738/article/details/116646412
https://www.cnblogs.com/DanielL916/p/16177853.html
https://amore.blog.csdn.net/article/details/118547668

 

posted on 2022-09-15 14:45  腾逸  阅读(3973)  评论(0编辑  收藏  举报