Jackson2多对多反序列化 [英] Jackson2 many to many deserialization
本文介绍了Jackson2多对多反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个类Event和Users,它们之间具有多对多关系.
I have two classes Events and Users which have a many to many relationship.
public class Event {
private int id;
private List<Users> users;
}
public class User {
private int id;
private List<Event> events;
}
我已阅读@JsonIdentityInfo批注应该有帮助,但我看不到此类示例.
I have read @JsonIdentityInfo annotation is supposed to help but I cannot see an example of this.
推荐答案
您可以这样在两个类User
和Event
中使用@JsonIdentityInfo
:
You can use @JsonIdentityInfo
in the two classes User
and Event
this way:
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
@JsonIdentityInfo(generator = ObjectIdGenerators.UUIDGenerator.class, property="@UUID")
public class User
{
private int id;
private List<Event> events;
// Getters and setters
}
...和
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
@JsonIdentityInfo(generator = ObjectIdGenerators.UUIDGenerator.class, property="@UUID")
public class Event
{
private int id;
private List<User> users;
// Getters and setters
}
您可以根据需要使用任何ObjectIdGenerator
.现在,与多对多映射相对应的对象的序列化和反序列化将成功:
You can use any of the ObjectIdGenerator
s as appropriate. Now, serialization and deserialization of the objects that correspond to the many to many mapping will succeed:
public static void main(String[] args) throws IOException
{
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
Event event1 = new Event();
event1.setId(1);
Event event2 = new Event();
event2.setId(2);
User user = new User();
user.setId(10);
event1.setUsers(Arrays.asList(user));
event2.setUsers(Arrays.asList(user));
user.setEvents(Arrays.asList(event1, event2));
String json = objectMapper.writeValueAsString(user);
System.out.println(json);
User deserializedUser = objectMapper.readValue(json, User.class);
System.out.println(deserializedUser);
}
希望这会有所帮助.
这篇关于Jackson2多对多反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文