fastjson注意事项

2018-11-30  本文已影响0人  多关心老人
ParentBean parentBean = new ParentBean();
        parentBean.setName("father");
        ChildBean childBean = new ChildBean();
        childBean.setName("son");
        //下面2句代码是关键
        parentBean.setChildBean(childBean);
               //先注释这句
//      childBean.setParentBean(parentBean);
        List<Object> dataList = new ArrayList<>();
        dataList.add(parentBean);
        dataList.add(childBean);
        System.out.println(JSON.toJSONString(dataList));
        System.out.println(JSON.toJSONString(dataList, SerializerFeature.DisableCircularReferenceDetect));

ParentBeanChildBean相互持有对方引用。
上面代码中childBean先不设置parentBean,
打印结果

[{"childBean":{"name":"son"},"name":"father"},{"$ref":"$[0].childBean"}]
[{"childBean":{"name":"son"},"name":"father"},{"name":"son"}]

把注释打开,结果:

[{"childBean":{"name":"son","parentBean":{"$ref":".."}},"name":"father"},{"$ref":"$[0].childBean"}]

java.lang.StackOverflowError
    at com.alibaba.fastjson.serializer.SerializeWriter.writeFieldValueStringWithDoubleQuoteCheck(SerializeWriter.java:1378)

第一个打印正常,第二个因为禁止循环引用检测,导致序列化栈溢出了。

Jackson的ObjectMapper也有这个问题,不过默认就会报错,相比之下还是fastjson更人性化一些,不过需要在反序列化的时候也要用fastjson,否则反序列化结果不是你想要的。
ObjectMapper解决循环引用方法https://stackoverflow.com/questions/37388613/jackson-serialize-entity-with-self-reference
不建议对象循环引用,也不建议同时序列化parentBean和childBean,网络调用方很可能解析不了。

上一篇 下一篇

猜你喜欢

热点阅读