I am implementing a RESTful server inside my company. The workflow is very straight-forward: request
and response
. However, nothing is easy, the RESTful service is based on an existed project, which handles database operations, and the entities inside that project is pretty complex(a lot of interfaces and abstract classes).
Take this as a demo:
In class Zoo
, there is a set of IAnimal
. The when I tried to deserialize {"animals":[{"name":"1"},{"name":"2"}]}
into Zoo
instance, it will will have such error as below:
1 | com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.oshackers.quickstart.jackson.model.IAnimal, |
The error message is very clear.
(Note: For Jackson version 1.x, you may have other error, as find object as LinkedHashMap, cannot cast to SomeClass
.)
Solution 1 (wrapper our own Deserializer):
1 | public class AnimalDeserializer extends JsonDeserializer<Set<IAnimal>> { |
Then inside IZoo
:
1 | .class) (using = AnimalDeserializer |
Solution 2 (Use Jackson Annotation)
Modify IAnimal
as
1 | "@class") (use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = |
What are the differences between these two solutions?
Solution 1 will not bring side-effect to Serialization
, which means if a zoo instance is serialized, we will get the json like:
1 | { |
While solution 2, for the same zoo instance, it will print json string as
1 | { |
Now, I believe you know how solution 2 work. Have fun!
Find the demo code here: https://github.com/zhouhao/Jackson-Quick-Start/tree/master/src/main/java/com/oshackers/quickstart/jackson