问题产生的原因
Long类型的数据,如果我们在后端将结果序列化为json,直接传给前端的话,在Long长度大于17位时会出现精度丢失的问题。 java中的long能表示的范围比js中number大,也就意味着部分数值在js中存不下(变成不准确的值),比如此案例中Id最后两位直接变成了0
解决方案
添加配置类
package baselib.cunyt.cn.common.mvc; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; 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; import java.math.BigInteger; /** * 解决java Long转json精度丢失的问题 * * @author wupeiguo */ @Configuration public class ApiMvcConfiguration { @Bean @Primary @ConditionalOnMissingBean(ObjectMapper.class) public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) { ObjectMapper objectMapper = builder.createXmlMapper(false).build(); // 全局配置序列化返回 JSON 处理 SimpleModule simpleModule = new SimpleModule(); //JSON Long ==> String //超长整 simpleModule.addSerializer(BigInteger.class, ToStringSerializer.instance); //长整 simpleModule.addSerializer(Long.class,ToStringSerializer.instance); //长整 simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance); objectMapper.registerModule(simpleModule); return objectMapper; } }
转载自:
https://blog.csdn.net/YangYF1997/article/details/119828164
https://www.csdn.net/tags/Mtjagg0sMDI1NzMtYmxvZwO0O0OO0O0O.html
标签:数据类型,springframework,Long,org,import,simpleModule,序列化 From: https://www.cnblogs.com/galo/p/16868007.html