gpt4 book ai didi

json - Jackson2 多对多反序列化

转载 作者:行者123 更新时间:2023-12-01 07:45:29 26 4
gpt4 key购买 nike

我有两个类 Events 和 Users,它们具有多对多关系。

public class Event {

private int id;

private List<Users> users;
}

public class User {
private int id;

private List<Event> events;
}

我已阅读 @JsonIdentityInfo 注释应该有所帮助,但我看不到这方面的示例。

最佳答案

您可以使用 @JsonIdentityInfo在两个类UserEvent这样:

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
}

您可以使用 <a href="http://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/ObjectIdGenerator.html" rel="noreferrer noopener nofollow">ObjectIdGenerator</a> 中的任何一个视情况而定。现在,多对多映射对应的对象的序列化和反序列化就成功了:

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);
}

希望这对您有所帮助。

关于json - Jackson2 多对多反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17987789/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com