object-->json (“$ref“: “..“) -->map

对象中互相调用会导致循环引用{"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"}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值