Reputation: 12366
I'm using Jackson and want to serialize subclass' fields into subelement. Unfortunately Jackson has awful documentation.
@JsonRootName(value = "subclass")
public class ProfilerTask extends Task {
private int age;
private int grade;
public ProfilerTask(String name, Date createdOn, int age, int grade) {
super(name, createdOn);
this.age = age;
this.grade = grade;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @return the grade
*/
public int getGrade() {
return grade;
}
}
I'm getting this: {"name":"test task","createdOn":1372771395040,"age":25,"grade":4}
, while I actually want subclass's fields to be a subelement.
Upvotes: 1
Views: 1038
Reputation: 38665
I think, you should think about composition instead of inheritance. But if you really want to have inheritance you have to change POJO class. You can create new internal class and move all properties and fields into this new class. See my example:
public class ProfilerTask extends Task {
private Subclass subclass;
public ProfilerTask(String name, long createdOn, int age, int grade) {
super(name, createdOn);
this.subclass = new Subclass();
this.subclass.age = age;
this.subclass.grade = grade;
}
public Subclass getSubclass() {
return subclass;
}
@JsonIgnore
public int getAge() {
return subclass.age;
}
@JsonIgnore
public int getGrade() {
return subclass.grade;
}
public class Subclass {
private int age;
private int grade;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
}
}
Now, please see my simple main method:
ObjectMapper mapper = new ObjectMapper();
ProfilerTask task = new ProfilerTask("test task", 1372771395040L, 25, 4);
System.out.println(mapper.writeValueAsString(task));
This program prints:
{"name":"test task","createdOn":1372771395040,"subclass":{"age":25,"grade":4}}
I think this is the simplest way to create sub-element in JSON with Jackson.
Upvotes: 1