Saturday, February 13, 2016

Polymorphic endpoints with Jackson

When you are designing an application model, one of the most useful techniques is the polymorphism. This allow to us , to write more generic code, more maintainable, and sometimes OCP  complaint (Open Close Principle, see SOLID).

The same concept, applies when you are designing a Rest API. In other words, the same endpoint can admit different Json structures. With this technique, you avoid to create a different endpoints for the different Json formats. Then your Rest API is more confortable and more friendly for your clients.

Imagine you have to design and endpoint to create task. But you have to be able to create user task and group task. The first step is to design our request model for this endpoint.


As you can see down, with the annotation @JsonTypeInfo we are telling to Jackson (Jackson is the library used in this example to convert Json files to java objects) what property has to use to find the class to deserialize. When the property informed in the Json input file is "group", jackson tries to deserialize to GroupCreateTaskRequest object or to GroupCreateTaskRequest when is "user". On the other hand, with the annotation @JsonSubType we are mapping the type property value with the child class.

Finally, our Rest controller looks like that.



You can find the code of this example here.

No comments:

Post a Comment