Spring Boot响应体中BigInteger值不准确的解决方法
解决Spring Boot中BigInteger字段JSON序列化精度丢失问题
问题根源
JavaScript的Number类型最多只能精确表示小于2^53的整数,你数据库里的数值12345678912345678912远超过这个阈值。默认情况下Jackson(Spring Boot默认的JSON序列化工具)会把BigInteger转成Number类型返回,自然就丢了精度。
可行解决方案
1. 给单个字段加注解,序列化为字符串
直接在实体类的old字段上添加Jackson的序列化注解,强制转成字符串输出:
import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import java.math.BigInteger; public class YourEntity { @JsonSerialize(using = ToStringSerializer.class) private BigInteger old; // 这里写getter、setter方法 }
这样返回的JSON里old就是完整的字符串形式,前端拿到后可以直接使用,不会有精度损失。
2. 全局配置Jackson,统一处理所有BigInteger字段
如果项目里有多个BigInteger字段需要处理,写个配置类全局设置更省事:
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.math.BigInteger; @Configuration public class JacksonConfig { @Bean public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); // 给BigInteger类型注册字符串序列化器 module.addSerializer(BigInteger.class, ToStringSerializer.instance); mapper.registerModule(module); return mapper; } }
配置生效后,所有BigInteger类型的字段都会自动序列化为字符串。
3. 通过配置文件全局开启(Spring Boot 2.x+适用)
不想写代码的话,直接在配置文件里加一行配置就行:
如果是application.properties:
spring.jackson.serialization.write-biginteger-as-string=true
如果是application.yml:
spring: jackson: serialization: write-biginteger-as-string: true
这种方式最简洁,不需要额外编写Java类。
内容的提问来源于stack exchange,提问作者PureFlow
相关产品推荐
相关产品推荐

