Spring Boot中接口数据字段为 Long 类型时,前端number精度丢失问题解决方案
Spring Boot中接口数据字段为 Long 类型时,前端number精度丢失问题解决方案
在Spring Boot中,当接口数据字段为 Long 类型时,返回页面的JSON中该字段通常会被序列化为数字类型。
例如,一个Java对象中有一个 Long 类型的属性 id ,值为 1234567890123L ,在返回的JSON中会表示为 {"id":1234567890123} 。
不过,JavaScript中 Number 类型的安全整数范围是 -2^53 到 2^53 ,如果 Long 类型的值超出这个范围,在前端JavaScript处理时可能会出现精度丢失问题。为避免该问题,可以在将 Long 类型数据返回给前端时,将其转换为 String 类型。可以使用 Jackson 的 @JsonSerialize 注解来实现,示例代码如下:
java
import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
public class MyObject {
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
// 省略其他属性和方法
} 这样,在返回JSON时, id 字段就会被序列化为字符串类型,能有效避免前端的精度丢失问题。
在Spring Boot中,可以通过配置 Jackson 来全局设置 Long 类型字段在返回JSON时序列化为字符串类型。 以下是两种常见的方法:
1.通过配置类 创建一个 Jackson 的配置类,在类中定义一个 Bean 来配置 ObjectMapper 。示例代码如下:
java
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;
@Configuration public class JacksonConfig {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
// 将Long类型序列化为字符串
module.addSerializer(Long.class, ToStringSerializer.instance);
// 处理Long类型的数组或集合
module.addSerializer(Long[].class, new ToStringSerializer(false));
objectMapper.registerModule(module);
return objectMapper;
}
}
2.通过应用配置文件 在 application.properties 或 application.yml 文件中添加配置,告诉 Jackson 将 Long 类型序列化为字符串。示例如下:
yaml
spring: jackson: serialization: WRITE_NUMBERS_AS_STRINGS: true
上述两种方法都可以实现将 Long 类型字段全局序列化为字符串类型,你可以根据项目的实际情况选择合适的方式。