fastjson问题汇总

前端之家收集整理的这篇文章主要介绍了fastjson问题汇总前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1、返回json有部分数据有bug,转换json异常$ref,如:“奶粉” || 已解决 // 解决循环引用,对应的配置见spring-web.xml

解决方式1:

JSONObject.toJSONString(list,SerializerFeature.DisableCircularReferenceDetect);

解决方式2:

<bean id="fastJsonHttpMessageConverter"
class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
<property name="features">
<array value-type="com.alibaba.fastjson.serializer.SerializerFeature">
<value>DisableCircularReferenceDetect</value>
</array>
</property>
</bean>
<bean id="DisableCircularReferenceDetect" class="org.springframework.beans.factory.config.FieldRetrievingfactorybean">
<property name="staticField" value="com.alibaba.fastjson.serializer.SerializerFeature.DisableCircularReferenceDetect"></property>
</bean>

2、fastjson对于float、double类型的数字精度丢失的问题

com.alibaba.fastjson.serializer.DoubleSerializer#write 有这么一段:

doubleText = Double.toString(doubleValue);
                if (doubleText.endsWith(".0")) {
                    doubleText = doubleText.substring(0,doubleText.length() - 2);
                }

对于float类型也是一样,com.alibaba.fastjson.serializer.FloatCodec#write

解决方案:

、重写序列化器;

添加ValueFilter:

ValueFilter filter = new ValueFilter() {
            @Override
            public Object process(Object object,String name,Object value) {
                if (value instanceof BigDecimal || value instanceof Double || value instanceof Float) {
                    return new BigDecimal(value.toString());
                }
                return value;
            }
        };

猜你在找的Json相关文章