现象
代码
Map<Long, Person> map = new HashMap<>();
Person person = new Person();
person.setName("Bruce");
map.put(1L, person);
List<ContainerClass> list = new ArrayList<>();
ContainerClass containerClass = new ContainerClass();
containerClass.setP1(map.get(1L));
containerClass.setP2(map.get(1L));
list.add(containerClass);
String s = JSON.toJSONString(list);
System.out.println(s);
结果
[{"p1":{"name":"Bruce"},"p2":{"$ref":"$[0].p1"}}]
解决
方案一
String s = JSON.toJSONString(list, SerializerFeature.DisableCircularReferenceDetect);
方案二
Person p2 = new Person();
BeanUtils.copyProperties(map.get(1L), p2);
containerClass.setP2(p2);
结果
[{"p1":{"name":"Bruce"},"p2":{"name":"Bruce"}}]
网友评论