1、场景

由于在项目中使用的模型是JSON结构的,最近在往模型中put同一对象后,发现toJSONString()后的结果中有$ref,导致在使用过程中出现问题;模拟如下:

JSONObject user = JSON.parseObject("{\"id\":\"007\", \"name\":\"James Bond\"}");
JSONObject obj = new JSONObject();
obj.put("Alpha", user);
obj.put("Bravo", user);

String json = obj.toJSONString();
System.out.println(json);

输出:

{"Alpha":{"name":"James Bond","id":"007"},"Bravo":{"$ref":"$.Alpha"}}

或者还可能出现:"$ref": "$.children[2].properties.foo.bar[0]"这样的结构。

2、处理方法

  • 使用SerializerFeature.DisableCircularReferenceDetect配置项
JSONObject user = JSON.parseObject("{\"id\":\"007\", \"name\":\"James Bond\"}");
JSONObject obj = new JSONObject();
obj.put("Alpha", user);
obj.put("Bravo", user);

String json = JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect);
System.out.println(json);

输出:

{"Alpha":{"name":"James Bond","id":"007"},"Bravo":{"name":"James Bond","id":"007"}}
  • 使用clone()方法
JSONObject user = JSON.parseObject("{\"id\":\"007\", \"name\":\"James Bond\"}");
JSONObject obj = new JSONObject();
obj.put("Alpha", user);
obj.put("Bravo", user.clone());

String json = obj.toJSONString();
System.out.println(json);

输出:

{"Alpha":{"name":"James Bond","id":"007"},"Bravo":{"name":"James Bond","id":"007"}}
  • 使用不同的对象
String user = "{\"id\":\"007\", \"name\":\"James Bond\"}";
JSONObject alpha = JSON.parseObject(user);
JSONObject bravo = JSON.parseObject(user);
JSONObject obj = new JSONObject();
obj.put("Alpha", alpha);
obj.put("Bravo", bravo);

String json = JSON.toJSONString(obj);
System.out.println(json);

输出:

{"Alpha":{"name":"James Bond","id":"007"},"Bravo":{"name":"James Bond","id":"007"}}
参考资料:

Fastjson-fastjson中$ref对象重复引用问题

JSONObject.toJSONString()出现$ref:"$."的解决办法(重复引用)