想要解决long类型丢失问题,必要将long类型转换为String类型再传输,一共有三种解决方案
方案一:注解方式:实体类中增加注解
/** 主键ID */
@Id
@GeneratedValue(generator = "ID")
@GenericGenerator(name = "ID", strategy = "assigned")
@Column(insertable = false, name = "ID", nullable = false,length = 64)
@JsonSerialize(using = ToStringSerializer.class)//解决long精度丢失问题
private Long id;
方案二:自定义ObjectMapper (推荐):启动类中增加配置
@SpringBootApplication
@EnableTransactionManagement
public class Application {
/**
* 解决Jackson导致Long型数据精度丢失问题
* @return
*/
@Bean("jackson2ObjectMapperBuilderCustomizer")
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
Jackson2ObjectMapperBuilderCustomizer customizer = new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
jacksonObjectMapperBuilder.serializerByType(Long.class, ToStringSerializer.instance)
.serializerByType(Long.TYPE, ToStringSerializer.instance);
}
};
return customizer;
}
public static void main(String[] args){
SpringApplication.run(Application.class,args);
}
}
方案三:配置参数:在yml或properties中增加配置
jackson:
generator:
write_numbers_as_strings: true
该方式会强制将所有数字全部转成字符串输出,这种方式的优点是使用方便,不需要调整代码;缺点是颗粒度太大,所有的数字都被转成字符串输出了,包括按照timestamp格式输出的时间也是如此。不推荐
参考:https://blog.csdn.net/haha_66666/article/details/86494853