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; }
标签:JsonFormat,17,Long,丢失,import,ToStringSerializer,com,精度,build From: https://www.cnblogs.com/Fooo/p/18235277