Spring Boot接口返回Long类型的数据时丢失精度的全局处理
1、问题
当实体类中的字段为Long类型时,通过Ajax请求返回给前段,在js中数据会丢失精度
直接通过postman请求或通过浏览器请求,看下响应则不会丢失精度
2、处理方式
1、使用@JsonSerialize注解
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
2、使用@JsonFormat注解
@JsonFormat(shape = JsonFormat.Shape.STRING)
private Long id;
3、全局配置ObjectMapper Bean
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
@Slf4j
@Configuration
public class JacksonConfig {
/**
* Jackson对象映射器
* @param builder builder
* @return ObjectMapper
*/
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
try {
// 将Long类型返回时修改为String类型
builder.serializerByType(Long.TYPE, ToStringSerializer.instance);
builder.serializerByType(Long.class, ToStringSerializer.instance);
} catch (Exception e) {
log.info("Serialization exception!");
}
return builder.build();
}
}