Thursday, July 19, 2012

Jackson Polymorphism

You can handle polymorphism with Jackson using the following annotations at the class level:
j@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "accountType")
@JsonSubTypes({
   @Type(value = AdminAccount.class, name =”ADM”),
   @Type(value = NormalAccount.class, name =”NML”)
})

This will tell Jackson to map the object to the "AdminAccount" class when the "accountType" property is "ADM", and to the "NormalAccount" class when the "accountType" property is "NML".

Other options are available, such as directly using the class name.

One "gotcha" I discovered is that the "accountType" property must not be implemented in the POJO class. If there is an "accountType" property in the class, it will be null when it's time to work with it in Java. In Java-land, you'll have to use "instanceof" to know what object it is.

A article with more detailed examples: http://programmerbruce.blogspot.com/2011/05/deserialize-json-with-jackson-into.html

No comments:

Post a Comment