问题重现
商品和商品类型是 ManyToOne 的关系 和 OneToMany 的关系, 查询商品信息时会级联查询其他商品类型的结构, 返回 json 数据时, 会出现 $ref
. 如下:
{ "rows": [ { "goodstype": { "name": "水果", "uuid": 1 }, "inprice": 5.55, "name": "苹果", "origin": "山东", "outprice": 8, "producer": "红富士", "unit": "箱", "uuid": 1 }, { "goodstype": { "$ref": "$.rows[0].goodstype" -> FastJson的“循环引用检测”的问题 }, "inprice": 6.23, "name": "菠萝", "origin": "广州", "outprice": 8, "producer": "绿富士", "unit": "箱", "uuid": 3 } ], "total": 7 }
解决办法
使用 FastJson 提供的 SerializerFeature.DisableCircularReferenceDetect
这个序列化选项,关闭引用检测
/** * fastjson中$ref对象重复引用问题 * * 介绍: * FastJson 提供了 SerializerFeature.DisableCircularReferenceDetect 这个序列化选项,用来关闭引用检测。 * 关闭引用检测后,重复引用对象时就不会被 $ref 代替,但是在循环引用时也会导致 StackOverflowError 异常。 * * 用法: * JSON.toJSONString(object, SerializerFeature.DisableCircularReferenceDetect); */ public void listByPage(){ int firstResult = (page -1) * rows; List<T> list = baseBiz.getListByPage(t1, t2, param, firstResult, maxResult); long total = baseBiz.getCount(t1, t2, param); Map<String, Object> mapData = new HashMap<String, Object>(); mapData.put("total", total); mapData.put("rows", list); // 把 goods 列表转JSON字符串, DisableCircularReferenceDetect 禁止循环引用 String listString = JSON.toJSONString(mapData,SerializerFeature.DisableCircularReferenceDetect); WebUtil.write(listString); }
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于