I have written a method which returns an array. This array contains
different subclass object instances. However, the json output only contains
the properties of the superclass.
I have created another program, trying to use jackson's ObjectMapper to
generate json. The output contains both properties of superclass and
subclass. And jackson's output does not contain a "person" property name
field.
How can I generate the output as same as the output generated by jackson
library?
Thanks.
Franz
Here is the example.
The model class :
@XmlRootElement
public class Person {
private String name;
/* getter and setter */
}
public class Staff {
private int rank;
/* getter and setter */
}
The restful service :
@Path("/test")
@POST
@Produces(MediaType.APPLICATION_JSON)
public Person[] test() {
Staff staff = new Staff();
staff.setName("Franz Wong");
staff.setRank(5);
Staff staff2 = new Staff();
staff2.setName("Peter Wong");
staff2.setRank(1);
Person[] persons = new Person[2];
persons[0] = staff;
persons[1] = staff2;
return persons;
}
Jackson version for testing code :
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(System.out, persons); // setup of persons array is
the same
The json output:
{"person":[{"name":"Franz Wong"},{"name":"Peter Wong"}]}
The json output from jackson's ObjectMapper.
[{"rank":5,"name":"Franz Wong"},{"rank":1,"name":"Peter Wong"}]