Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

同一个list多个元素引用同一个HashMap实例,序列化失败 #3643

Closed
sheepzh opened this issue Feb 8, 2021 · 3 comments
Closed

Comments

@sheepzh
Copy link

sheepzh commented Feb 8, 2021

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"}}
  1. 将两个对象一起放入同一个 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;
}
@shenshaoming
Copy link

这似乎是有意为之:
image

@biyanwen
Copy link
Contributor

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

@sheepzh sheepzh closed this as completed Feb 26, 2021
@antdong
Copy link

antdong commented Sep 9, 2022

DisableCircularReferenceDetect

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants