JSONObject字符串中出现$ref的问题
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"}}