Long类型返回给前端精度丢失问题(解决方案)
为了将 Java 中的 Long
类型在返回给前端时自动转换为 String
(避免 JavaScript 处理大整数时的精度丢失问题),可以使用 Jackson 注解。具体有以下两种常用方式:
方案一:使用 @JsonSerialize
注解(推荐)
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;/*** 转交记录主键*/
@JsonSerialize(using = ToStringSerializer.class) // 将 Long 序列化为字符串
private Long id;
方案二:使用 @JsonFormat
注解
import com.fasterxml.jackson.annotation.JsonFormat;/*** 转交记录主键*/
@JsonFormat(shape = JsonFormat.Shape.STRING) // 指定数字类型序列化为字符串
private Long id;
为什么需要转换?
JavaScript 的整数最大安全值为 2^53 - 1
(约 9e15
),而 Java 的 Long
最大值 9,223,372,036,854,775,807
(约 9e18
)超出该范围时,前端会出现精度丢失(如末尾几位变成 0
)。转换为字符串可完美解决此问题。
效果对比
假设 id = 1234567890123456789
:
// 未转换(错误):
{ "id": 1234567890123456700 } // 末尾两位精度丢失// 转换后(正确):
{ "id": "1234567890123456789" } // 字符串形式精确传递
依赖要求
确保项目中已引入 Jackson 库(Spring Boot 默认包含):
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId>
</dependency>
⚠️ 注意:如果字段可能为
null
,需与前端约定空值处理逻辑(如返回""
或null
),两种注解默认会序列化为null
。