[alibaba/fastjson]同一个list多个元素引用同一个HashMap实例,序列化失败

2023-12-20 974 views
4

fastjson.version = 1.2.75

  1. 创建两个 Person 类实例,并引用同一个 HashMap 实例

        Map<String, String> roles = new HashMap<>();
        roles.put("1", "Master");
        roles.put("2", "Student");

        Person p1 = new Person(roles);
        Person p2 = new Person(roles);
  1. 分别序列化,没有问题
        System.out.println(JSON.toJSONString(p1)); 
        System.out.println(JSON.toJSONString(p2));       
    {"roles":{"1":"Master","2":"Student"}}        
    {"roles":{"1":"Master","2":"Student"}}
  2. 将两个对象一起放入同一个 LinkedList 之后再序列化,BUG happens...

        List<Person> oneGroupOfPeople = new LinkedList<>();
        oneGroupOfPeople.add(p1);
        oneGroupOfPeople.add(p2);
        System.out.println(JSON.toJSONString(oneGroupOfPeople));
    [{"roles":{"1":"Master","2":"Student"}},{"roles":{"$ref":"$[0].roles"}}]

Person 类的定义

@Data
@AllArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
static class Person {
    Map<String, String> roles;
}

回答

2

这似乎是有意为之: image

1

貌似是你使用的姿势不对 将 System.out.println(JSON.toJSONString(oneGroupOfPeople)); 替换为下面的代码即可正常输出 System.out.println(JSON.toJSONString(oneGroupOfPeople, SerializerFeature.DisableCircularReferenceDetect));

5

DisableCircularReferenceDetect

这样就关闭了循环引用检测了