long类型精度丢失问题的三种解决方案 (在Long长度大于17位时会出现精度丢失的问题)
Posted on 2024-06-06 15:46 且行且思 阅读(544) 评论(0) 编辑 收藏 举报1. 简介
对于Long类型的数据,如果我们在Controller层将结果序列化为json,直接传给前端的话,在Long长度大于17位时会出现精度丢失的问题
2. 解决方案
2.1 注解
2.1.1 @JsonFormat
@JsonFormat(shape =JsonFormat.Shape.STRING)
2.1.2 @JsonSerialize
@JsonSerialize(using = ToStringSerializer.class)
2.1.3 详情
package com.king.entity; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import lombok.Data; import lombok.EqualsAndHashCode; import java.io.Serializable; /** * @author King * @version 1.0 * @description TODO * @date 2023/9/5 10:19 */ @Data @EqualsAndHashCode(callSuper = false) public class user implements Serializable { //方式一 @JsonFormat(shape = JsonFormat.Shape.STRING) private Long id; private String username; private String password; //方式二 @JsonSerialize(using = ToStringSerializer.class) private String userId; }
2.2 ObjectMapper
在spring boot的启动类或者spring的配置类里面添加bean
/** * @description Long类型精度类型丢失 * @param mapperBuilder * @return com.fasterxml.jackson.databind.ObjectMapper * @author King * @date 2023/9/5 10:33 */ @Bean public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder mapperBuilder) { ObjectMapper build = mapperBuilder.createXmlMapper(false).build(); build.setSerializationInclusion(JsonInclude.Include.NON_NULL); SimpleModule module = new SimpleModule(); module.addSerializer(Long.class, ToStringSerializer.instance); module.addSerializer(Long.TYPE, ToStringSerializer.instance); build.registerModule(module); return build; }