In the following Jackson/Java code that serializes objects into JSON, I am getting this:
{\"animal\":{\"x\":\"x\"}}
However, what I actually wa
As per this announement, Jackson 1.5 implements full polymorphic type handling, and trunk now has that code integrated.
There are two simple ways to make this work:
This is the only way I can think of to do it, and it is ugly. Is there a better way?
@JsonWriteNullProperties(false)
public static class AnimalContainer
{
private Animal animal;
public Animal getCat()
{
return animal instanceof Cat ? animal : null;
}
public void setCat(Cat cat)
{
this.animal = cat;
}
public Animal getDog()
{
return animal instanceof Dog ? animal : null;
}
public void setDog(Dog dog)
{
this.animal = dog;
}
public Animal getFish()
{
return animal instanceof Fish ? animal : null;
}
public void setFish(Fish fish)
{
this.animal = fish;
}
}
This is probably not the answer you are looking for, but there are plans to implement proper "polymorphic deserialization" (and necessary support on serialization for it), for Jackson version 1.4 or so (i.e. not the next one, 1.3, but one after that).
For current version, you have to implement custom serializers/deserializers: I would probably just define factory method for deserialization, and type getter for serializer (define 'getAnimalType' or whatever in abstract base class as abstract, override in sub-classes -- or even just implement in base class, output class name of instance class?).
Anyway, just in case it matters, here are underlying problems wrt implementing handling of sub-classes with JSON, and without schema language (since json doesn't really have widely used one):
These are solvable problems, but not trivially easy to solve. :-)