开发中,后端过长的Long类型数据返回给前端,精度丢失问题,后面几位填充0的情况如何解决?
由于过长的Long类型数据返回会产生精度问题,所以我们可以将它转换成String类型后,再序列化返回给到前端。
解决方案:两种方法
第一种:注解的方法
//在需要转换成字符串的字段上加上这个注解
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
以上方式需要在每个需要转换的字段上都加上这个注解,比较麻烦。
第二种方法:全局解决的方法:
将一下Bean对象进行配置,创建出来给到spring容器管理。
创建对象映射,将Long类型的数据,转换成String类型后序列化返回给前端。
@Bean
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder){
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
return objectMapper;
}