I'm using RESTeasy to convert a json from the payload to a POJO in the web server. I encounter a problem when one of those POJO member is generic.
For example:
public class MainPOJO
{
private MyParentClass c;
[...]
}
public class MyParentClass
{
[...]
}
public class MyFirstChildClass extends MyParentClass
{
private int number;
[...]
}
public class MySecondChildClass extends MyParentClass
{
private boolean isTrue;
[...]
}
In the request payload (PUT) made by the client, you can found something like this json (notice that I send a MyFirstChildClass equivalent in json format in the "c" attribute):
{
c: {number:10}
}
Is there any way to tell RESTeasy that the property "c" in the MainPOJO can be either an instance of MyParentClass, MyFirstChildClass or MySecondChildClass?
Currently, it just try to instanciate a MyParentClass new instance but throw an error saying that property, for exemple, "number" is not mark as ignorable. But I wish it could be more intelligent and instantiate an object from the right class in the tree according to the properties in the json.
Is it possible?
Thanks!
Assuming you are using the Jackson provider, then the best way to handle this would be via the JsonTypeInfo
annotation. Using it informs Jackson that you want type hints included in generated JSON, that it can use to resolve the actual type when it comes to de-serialization.
To always include type information when your MyParentClass
is being serialized, you would annotate the class itself:
@JsonTypeInfo(use=Id.CLASS, include=As.PROPERTY, property="class")
public class MyParentClass {
}
Alternatively, to only include the type information for MyParentClass
when a MainPojo
object is being serialized, you would annotate the field:
public class MainPOJO {
@JsonTypeInfo(use=Id.CLASS, include=As.PROPERTY, property="class")
private MyParentClass c;
}
Refer to the Jackson documentation on JsonTypeInfo for more detail on overrides and options.