Hi Guys in my previous blog JSON deserialize generic types using Gson and Jackson I talked about how you can deserialize json in Java Generics. Now in this blog post we are going to learn how to deserialize json into Java class which doesn’t have default constructor. For this blog I am using Jackson library.
Almost all frameworks requires default/no-argument constructor in your class. Because these frameworks use reflection to create objects by invoking default constructor. But if there is no default constructor present in class then its hard to instantiate using reflection. Let’s assume we have a class with no-args constructor (only a parameterized constructor present) and we want to deserialize it.
And a json file
There are two ways in Jackson to deserialize this type of classes.
- Custom deserializer
- Mixin Annotations
1. Custom Deserializer
In Custom Deserializer you will create a class and extend it with
com.fasterxml.jackson.databind.JsonDeserializer and override its abstract method
deserialize(). This class gives you full control, you’ll get json in
com.fasterxml.jackson.core.JsonParser. Now you can map json properties with class properties. In my case I am creating
Now we need to register above deserializer in
com.fasterxml.jackson.databind.ObjectMapper. So that, while deserializing UserProfile class it use
In above code we are adding our Deserializer in
com.fasterxml.jackson.databind.module.SimpleModuleand that module is registered in
com.fasterxml.jackson.databind.ObjectMapper. Similarly, you can register deserializers for other classes too.
2. Mixin Annotations
Jackson provides another way of doing this by using Mixin Annotations. You can read about Jackson Mixin here. In our class
UserProfile there is no default constructor, it has a parameterized constructor. Let’s checkout how to create mixin for our class.
That’s it !!
We have created a constructor same as in
UserProfileclass and marked it with
com.fasterxml.jackson.annotation.JsonCreatorannotation. This will tell
com.fasterxml.jackson.databind.ObjectMapperthis is how target class (
UserProfile) constructor looks and constructor parameters are marked with
Now checkout how to register this mixin class in
Enjoy !!!! ☺☺