项目中很多时候都会用到json,常用的有fastjson,Jackson等等这些,有时候为了统一,我们通常就会约定使用某一种。
不管使用哪种,Spring MVC返回个前段Long类型的数据时,js在获取数据时会丢失精度,从而造成数据的不准确,解决方式呢,就是在序列化时,会将Long类型的数据转化为String类型
在使用Spring MVC默认的Jackson时,我们可以这么做:
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter jackson2HttpMessageConverter =
new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(BigInteger.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
jackson2HttpMessageConverter.setObjectMapper(objectMapper);
converters.add(jackson2HttpMessageConverter);
converters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
}
}
当然,有时候项目中也可能会统一约定使用了fastjson,然而Spring MVC中默认是使用了Jackson的
在Spring Boot中将Jackson替换为fastjson一般会有两种方式:
第一种:
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean
public HttpMessageConverters fastJsonHttpMessageConverter() {
return new HttpMessageConverters(new FastJsonHttpMessageConverter());
}
}
第二种:
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter fastConverter =
new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
fastConverter.setFastJsonConfig(fastJsonConfig);
converters.add(fastConverter);
}
}
替换成fastjson之后,对于精度丢失问题,我们可以这么去做:
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter fastConverter =
new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
SerializeConfig serializeConfig = SerializeConfig.globalInstance;
serializeConfig.put(BigInteger.class, ToStringSerializer.instance);
serializeConfig.put(Long.class, ToStringSerializer.instance);
serializeConfig.put(Long.TYPE, ToStringSerializer.instance);
fastJsonConfig.setSerializeConfig(serializeConfig);
fastConverter.setFastJsonConfig(fastJsonConfig);
converters.add(fastConverter);
}
}