使用fast json把java对象列表通过循环生成json 出现 “$ref“:“$.list

47 篇文章 0 订阅
5 篇文章 0 订阅

首先

引用标识说明:

“$ref”:”..” 上一级
“$ref”:”@” 当前对象,也就是自引用
“$ref”:”$” 根对象
{"$ref":"../.."} 引用父对象的父对象

局部方式

player3=JSONObject.parseObject(JSON.toJSONString(player3,SerializerFeature.DisableCircularReferenceDetect));

普通的spring项目的话,用xml配置

<mvc:annotation-driven>  
        <mvc:message-converters register-defaults="true">  
            <bean  
                class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">  
                <property name="supportedMediaTypes">  
                    <array>  
                        <value>text/html;charset=UTF-8</value>  
                    </array>  
                </property>  
                <property name="features">  
                    <array>  
                        <value>WriteMapNullValue</value>  
                        <value>WriteNullStringAsEmpty</value>  
                        <!-- 全局关闭循环引用检查,最好是不要关闭,不然有可能会StackOverflowException -->
                        <value>DisableCircularReferenceDetect</value>
                    </array>  
                </property>  
            </bean>  
        </mvc:message-converters>  
    </mvc:annotation-driven>

如果springboot的话

public class FastJsonHttpMessageConverterEx extends FastJsonHttpMessageConverter{
    public FastJsonHttpMessageConverterEx(){
        //在这里配置fastjson特性(全局设置的)
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");    //自定义时间格式
        //fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue);  //正常转换null值
        //fastJsonConfig.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect);     //关闭循环引用
        this.setFastJsonConfig(fastJsonConfig);
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return super.supports(clazz);
    }
}

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
    .....
    @Bean
    public FastJsonHttpMessageConverterEx fastJsonHttpMessageConverterEx(){
        return new FastJsonHttpMessageConverterEx();
    }
}

配置这个DisableCircularReferenceDetect的作用是:决定了生成的“多个”JSON对象中,是否加载被引用的同一个对象的数据。

 

 

现在的问题:

全局关闭引用检测确实是方便,但是有可能的以后的代码越来越多的情况出现StackOverflowError。但是局部的关闭引用检测的话也有些小问题。JSON.toJSONString(object, SerializerFeature.DisableCircularReferenceDetect) 这个方法是把对象转为String对象,如果在@ResponseBody注解的方法里返回这个String对象的话,

String result = JSON.toJSONString(obj);
return result;

这种情况就相当于JSON.toJSONString() 这句话执行了两次。

对象=JSONObject.parseObject(JSON.toJSONString(对象,SerializerFeature.DisableCircularReferenceDetect));
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值