踩坑记录——后端传值到前端,精度缺失
程序员文章站
2022-04-14 09:21:17
...
1.问题
后端Long类型传值到前端,精度缺失
2.解决方式
方式一:
@Configuration
public class JacksonConfig {
/**
* Jackson全局转化long类型为String,解决jackson序列化时传入前端Long类型缺失精度问题
*/
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
Jackson2ObjectMapperBuilderCustomizer cunstomizer = new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
jacksonObjectMapperBuilder.serializerByType(BigInteger.class, ToStringSerializer.instance);
jacksonObjectMapperBuilder.serializerByType(Long.class, ToStringSerializer.instance);
// jacksonObjectMapperBuilder.serializerByType(Long.TYPE, ToStringSerializer.instance);
}
};
return cunstomizer;
}
}
方式二:
@Configuration
public class LongClassMessageConverter implements InitializingBean {
@Resource
ObjectMapper objectMapper;
private SimpleModule getSimpleModule() {
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(BigInteger.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
// 暂时放弃对小long的转换,约定与前端交互数据时,大Long全部转换成字符串
// simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
return simpleModule;
}
@Override
public void afterPropertiesSet() {
SimpleModule simpleModule = getSimpleModule();
objectMapper.registerModule(simpleModule);
}
}
推荐阅读