You must be shapeless, formless, like water. - Bruce Lee
Brief
Adding@RequestBody annotation on a @Controller endpoint, we automatically map the HttpRequest body to a Java object. But if we want to somehow get in the middle of the deserialization process, we'll take a look over some Jackson annotations.
Implementation
Annotation-based
Say we can receive an input like this ⬇️ where we have a field based on which we can differentiate between the types of objects. In our case, the type field.
We create a Vehicle abstract class holding the common field. And then, two more classes Car and Airplane, both extending Vehicle, each with their own properties.
The trick here is to use the @JsonTypeInfo and @JsonSubTypes annotations in order to tell Jackson how to differentiate between different objects and to which types to cast the input.
Now, on the controller, we can add the Vehicle abstract class on the request body and let Jackson do the magic.
Custom deserializer
What do we do if we don't have a field which tells us what kind of object it is? For example, we get payloads like this ⬇️ for Dogs and Snakes.
We first, model the classes similar to the previous example. We need an Animal abstract class and two more classes Dog and Snake which extend Animal .
In addition, we need our own custom deserializer through which we tell Jackson how to instantiate the objects we want.
And then, like before, we only add the Animal abstract class for the request's body type and that is it.
You can find the code in the Github repository here:
💡
Don't miss out on more posts like this! Susbcribe to our free newsletter!
💡
Currently I am working on a Java Interview e-book designed to successfully get you through any Java technical interview you may take. Stay tuned! 🚀