本文介绍了使用Jackson参考现有对象进行反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
JSON
{
"schools": [
{
"id": 1,
"name": "School A"
},
{
"id": 2,
"name": "School B"
}
],
"students": [
{
"id": 1,
"name": "Bobby",
"school": 1
}
]
}
如何将JSON映射到以下类中,以便将Bobby的学校映射到已经实例化的学校A.
How would I map the JSON into the following classes such that Bobby's school is mapped to the already instantiated School A.
public class School {
private Integer id;
private String name;
}
public class Student {
private Integer id;
private String name;
private School school;
}
我在学生班上尝试了一些奇怪的东西...
I've tried some weird stuff with the Student class...
public class Student {
private Integer id;
private String name;
private School school;
@JsonProperty("school")
public void setSchool(Integer sid) {
for (School school : getSchools()) {
if (school.id == sid) {
this.school = school;
break;
}
}
}
}
我遇到的问题是学校和学生同时都是从JSON解析的,所以我不知道如何获得学校名单。也许我应该单独解析这些,所以我先得到学校名单?
The problem I'm having is that both the schools and the students are being parsed from the JSON at the same time, so I'm not sure how to get a list of the schools. Maybe I should parse these separately so I have the list of schools first?
推荐答案
杰克逊会为你做这件事。只需使用 @JsonIdentityInfo
注释您的对象:
Jackson will do it for you. Just annotate your objects with @JsonIdentityInfo
:
@JsonIdentityInfo(scope=School.class, generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
public class School {
private Integer id;
private String name;
public School() {
}
public School(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@JsonIdentityInfo(scope=Student.class, generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
public class Student {
private Integer id;
private String name;
private School school;
public Student() {
}
public Student(Integer id, String name, School school) {
this.id = id;
this.name = name;
this.school = school;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public School getSchool() {
return school;
}
public void setSchool(School school) {
this.school = school;
}
}
public static void main(String[] args) throws IOException {
School school = new School(1, "St Magdalene's");
Student mary = new Student(1, "Mary", school);
Student bob = new Student(2, "Bob", school);
Student[] students = new Student[] {mary, bob};
// Write out
String serialized = mapper.writeValueAsString(students);
System.out.println("Serialized: " + serialized);
// Read in
Student[] deserialized = mapper.readValue(serialized, Student[].class);
}
这篇关于使用Jackson参考现有对象进行反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!