解决FastJson中ref重复引用问题

解决FastJson中”$ref重复引用”的问题,先来看一个例子吧:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public static void main(String[] args) {
UserGroup userGroup = new UserGroup().setName("UserGroup");

User user = new User("User");
for (int i = 0; i < 3; i++) {
userGroup.addUser(user);
}
Console.log(JSON.toJSONString(userGroup));
}


@Data
@AllArgsConstructor
static class User {
private String name;
}

@Data
@Accessors(chain = true)
static class UserGroup {
private String name;
private List<User> users = Lists.newArrayList();

public UserGroup addUser(User user) {
this.getUsers().add(user);
return this;
}
}

输出结果:

1
{"name":"UserGroup","users":[{"name":"User"},{"$ref":"$.users[0]"},{"$ref":"$.users[0]"}]}

上面的现象就是将user对象的引用重复使用造成了重复引用问题,Fastjson默认开启引用检测将相同的对象写成引用的形式:

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×