I'm trying to marshal/unmarshal the following class structure:
public class Zoo {
public String name;
public List<Animal> animals;
}
public class Animal {
public String species;
}
public class Lion extends Animal {
public int maxSpeed;
}
public class Owl extends Animal {
public int maxHeight;
}
I'm testing this using the following Jersey function:
@GET
@Produces(MediaType.APPLICATION_JSON)
public Zoo get() {
Zoo zoo = new Zoo();
zoo.name = "NY";
Lion lion = new Lion();
lion.species = "Lion";
lion.maxSpeed = 100;
Owl owl = new Owl();
owl.species = "Owl";
owl.maxHeight = 200;
List<Animal> animals = new ArrayList<>();
animals.add(lion);
animals.add(owl);
zoo.animals = animals;
return zoo;
}
Which returns the following json:
{
"name": "NY",
"animals": [{
"species": "Lion"
}, {
"species": "Owl"
}]
}
When I'm actually looking for an output like the following:
{
"name": "NY",
"animals": [{
"species": "Lion", "maxSpeed": 100
}, {
"species": "Owl", "maxHeight": 200
}]
}
I understand why the maxSpeed and maxHeight attributes are not coming up in json (well, I guess the library uses reflection, so it makes sense that when asking for all attributes it only gets those for Animal). But can't really figure out how to accomplish this. I unsuccessfully tried to create an XmlAdapter for the maxSpeed field (Lion class). Nothing happened. Which makes sense, because this is still an Animal.
The Animal class was originally abstract, but during the POST process moxy needs to instantiate it, so I removed the qualifier.
Could anyone please give me hint how to accomplish this?
It is important to mention that I need to go in both directions (marshal/unmarshal) and if this is not possible, I would appreciate other ideas about how to represent this in json (multiple animals can be there, even multiple lions and owls).