最近工作中遇到一个问题,java接口使用阿里的Fastjson返回数据时,Long型的数据总会出现精度丢失的情况。看了下源码,最终通过扩展FastJsonHttpMessageConverter类来解决,首先写一个类继承FastJsonHttpMessageConverter,并重写setFastJsonConfig方法,用来设置Long类型的序列化方式。
public class CustomFastJsonHttpMessageConverter extends FastJsonHttpMessageConverter {
@Override
public void setFastJsonConfig(FastJsonConfig fastJsonConfig) {
fastJsonConfig.getSerializeConfig().put(Long.class, new LongSerializer());
super.setFastJsonConfig(fastJsonConfig);
}
}
在写一个Long对应的序列化类,该类继承自ObjectSerializer
public class LongSerializer implements ObjectSerializer {
@Override
public void write(JSONSerializer jsonSerializer, Object o, Object o1, Type type, int i) throws IOException {
SerializeWriter out = jsonSerializer.getWriter();
//如果原数据为空,就写null
if (o == null) {
jsonSerializer.getWriter().writeNull();
return;
} else{
//如果原数据不为空,就toString,并写入
out.writeString(o.toString());
}
}
}
在spring配置的时候,不在配置FastJsonHttpMessageConverter,而是配置CustomFastJsonHttpMessageConverter
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<!-- 这里原先定义的是FastJsonHttpMessageConverter,现改成CustomFastJsonHttpMessageConverter-->
<bean class="com.fanniekey.extend.CustomFastJsonHttpMessageConverter">
<property name="fastJsonConfig" >
<bean class="com.alibaba.fastjson.support.config.FastJsonConfig"/>
</property>
<property name="supportedMediaTypes">
<list>
<value>application/json</value>
</list>
</property>
<property name="features">
<list>
<value>QuoteFieldNames</value>
<value>WriteDateUseDateFormat</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>