JSON工具学习记录FastJSON循环引用问题:最近基于他人项目做二次开发,遇到了循环引用的问题,简单来说A引用了B,B引用了C,C引用了A,那么转换json就会无休止的转换下去。
更复杂的情况,A中引用了B,B中引用了一个A的集合,比如广告引用了广告类型,广告类型里面又有该类型下的所属广告.
这种又叫做双向引用,个人感觉这种设计本身就不是很合理,当然还要看具体使用场景了.
广告类:
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 /** * @author Niu Li * @date 2016/8/12 */ public class ADEntity { private int id; private String name; //引用了一个广告实体类 private ADTypeEntity adTypeEntity; public ADEntity( int id, String name, ADTypeEntity adTypeEntity) { this .id = id; this .name = name; this .adTypeEntity = adTypeEntity; } //省略get和set }广告实体类:
? 1 2 3 4 5 6 7 8 9 10 11 12 13 import java.util.List; /** * @author Niu Li * @date 2016/8/12 */ public class ADTypeEntity { private int id; private String name; //引用了其广告集合 private List lists; //省略get和set }</adentity>测试代码:
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 public class TestApp { public static void main(String[] args) { //构造广告类型 ADTypeEntity adTypeEntity = new ADTypeEntity(); adTypeEntity.setId( 1 ); adTypeEntity.setName( "轮播图" ); //构造广告 ADEntity entity1 = new ADEntity( 1 , "图1" ,adTypeEntity); ADEntity entity2 = new ADEntity( 2 , "图2" ,adTypeEntity); ADEntity entity3 = new ADEntity( 3 , "图3" ,adTypeEntity); List lists = new ArrayList(); lists.add(entity1); lists.add(entity2); lists.add(entity3); //双向引用 adTypeEntity.setLists(lists); String result = JSON.toJSONString(entity1); System.out.println(result); } }</adentity></adentity>结果可以看到双向引用被替换成$ref了:
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 { "adTypeEntity" : { "id" : 1 , "lists" : [ { "$ref" : "$" }, { "adTypeEntity" : { "$ref" : "$.adTypeEntity" }, "id" : 2 , "name" : "图2" }, { "adTypeEntity" : { "$ref" : "$.adTypeEntity" }, "id" : 3 , "name" : "图3" } ], "name" : "轮播图" }, "id" : 1 , "name" : "图1" }两种解决办法就是哪里有循环引用,就过滤掉该字段.
得到结果
? 1 2 3 4 5 6 7 8 { "adTypeEntity" : { "id" : 1 , "name" : "轮播图" }, "id" : 1 , "name" : "图1" }这表明对于ADTypeEntity类只序列化id和name字段,这样的话就排除掉list集合引用了,得到的结果和上面一样.