json数据格式转换问题 循环引用

本文介绍如何使用FastJSON处理对象转JSON格式字符串,并解决循环引用问题。通过设置SerializerFeature.DisableCircularReferenceDetect特性,可以避免序列化过程中出现的循环引用导致的错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 fastjson将对象转化成 json格式字符串

1
        Map<String, Object> map = new HashMap<>();
2
        map.put("rows", pageBean.getList());//把分页数据的集合放到 map中
3
        map.put("total", pageBean.getTotalCount());//把总记录数放到map中
4
        HttpServletResponse response = ServletActionContext.getResponse();//获得response
5
        response.setContentType("text/html;charset=utf-8");//处理中文 
6
        String json = JSON.toJSONString(map,SerializerFeature.DisableCircularReferenceDetect)
7
         response.getWriter().println(json);//把map转换成json格式符串 输出到页面
8
        response.getWriter().flush();//刷新

相关博文

转:http://blog.csdn.NET/mephistodemon1/article/details/19118493

DisableCircularReferenceDetect来禁止循环引用检测:

JSON.toJSONString(..., SerializerFeature.DisableCircularReferenceDetect)

当进行toJSONString的时候,默认如果重用对象的话,会使用引用的方式进行引用对象。

[java]  view plain  copy
 
  1. "颜色": [  
  2.       {  
  3.         "$ref""$.itemSkuList[0].itemSpecificationList[0]"  
  4.       },   
  5.       {  
  6.         "$ref""$.itemSkuList[1].itemSpecificationList[0]"  
  7.       }  
  8.     ]  

循环引用

很多场景中,我们需要序列化的对象中存在循环引用,在许多的json库中,这会导致stackoverflow。在功能强大的fastjson中,你不需要担心这个问题。例如:

[java]  view plain  copy
 
  1. A a = new A();  
  2. B b = new B(a);  
  3. a.setB(b);  
  4. String text = JSON.toJSONString(a); //{"b":{"a":{"$ref":".."}}}  
  5. A a1 = JSON.parseObject(text, A.class);  
  6. Assert.assertTrue(a1 == a1.getB().getA());  

引用是通过"$ref"来表示的

引用描述
"$ref":".."上一级
"$ref":"@"当前对象,也就是自引用
"$ref":"$"根对象
"$ref":"$.children.0"基于路径的引用,相当于 root.getChildren().get(0)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值