对象中互相调用会导致循环引用{"test1":{"test2":{"$ref":".."}}}
循环引用代码
@Test
public void test1(){
Map<String,Object> map1 = new HashMap();
Map<String,Object> map2 = new HashMap();
map1.put("test1",map2);
map2.put("test2",map1);
String str = "";
str = JSONObject.toJSONString(map1);
// str = JSON.toJSONString(map1,SerializerFeature.DisableCircularReferenceDetect);
System.out.println(str);
Map<String,String> map = JSONObject.parseObject(str,Map.class);
}
控制台
【注】
参考:https://blog.csdn.net/hongxiancheng/article/details/84891828
引用符号
引用 | 描述 |
---|---|
"$ref":".." | 上一级 |
"$ref":"@" | 当前对象,也就是自引用 |
"$ref":"$" | 根对象 |
"$ref":"$.children.0" | 基于路径的引用,相当于 root.getChildren().get(0) |
重复引用:一个对象的多个属性同时引用同一个对象,或一个集合中同时添加了同一个对象
【分析】
【解决方案】
使用过滤器
// 定义过滤器,指定需要进行转换的属性。
SimplePropertyPreFilter filter = new SimplePropertyPreFilter("username", "password", "roles", "roleName");
// 转换成Json数据
tring json = JSON.toJSONString(user, filter);
System.out.println(json); // {"password":"123","roles":[{"roleName":"管理员"}],"username":"jack"}