fastjson中$ref的坑

相信不少人都遇到过,用fastjson进行序列化时会遇到属性出现$ref的情况,本质是fastjson在处理对象引用时默认不展开,需要自己指定序列化参数。写个DEMO演示一下:

 1 JSONObject json = new JSONObject();
 2 JSONObject prop = new JSONObject();
 3 prop.put("name", "test");
 4 prop.put("index", "1");
 5 json.put("propA", prop);        //引用同一个对象
 6 json.put("propB", prop);        //引用同一个对象
 7 
 8 //用不同方式序列化
 9 System.out.println(JSON.toJSONString(json));
10 System.out.println(json.toJSONString());
11 System.out.println(json.toString(SerializerFeature.DisableCircularReferenceDetect));
12 System.out.println(JSON.toJSONString(json, SerializerFeature.DisableCircularReferenceDetect));

输出结果如下:

{"propB":{"name":"test","index":"1"},"propA":{"$ref":"$.propB"}}
{"propB":{"name":"test","index":"1"},"propA":{"$ref":"$.propB"}}
{"propB":{"name":"test","index":"1"},"propA":{"name":"test","index":"1"}}
{"propB":{"name":"test","index":"1"},"propA":{"name":"test","index":"1"}}

可以看到序列化时需要加 SerializerFeature.DisableCircularReferenceDetect 才能得到正确的结果。

需要说明的是这个问题仅出现在fastjson 1.x版中,升级到fastjson 2.x后就没这个问题了,但是2.x部分API与之前不同,升级有一定的成本。

 

posted on 2023-05-12 16:02  BoyTNT  阅读(178)  评论(0编辑  收藏  举报

导航