我有两个类,事件和用户,有很多关系.
public class Event {
private int id;
private List<Users> users;
}
public class User {
private int id;
private List<Event> events;
}
Run Code Online (Sandbox Code Playgroud)
我已经读过@JsonIdentityInfo注释应该有帮助,但我看不到这个例子.
您可以使用@JsonIdentityInfo在两个类User和Event这种方式:
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
}
Run Code Online (Sandbox Code Playgroud)
......和
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
}
Run Code Online (Sandbox Code Playgroud)
您可以根据需要使用任何一个ObjectIdGenerator.现在,对应于多对多映射的对象的序列化和反序列化将成功:
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);
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
3923 次 |
| 最近记录: |