Jackson Mixin Annotation in Java

Posted By :Arun Singh |28th July 2018

Two methods for serializing or deserialize JSON using Jackson.

  • Modify in the POJO classes to add annotations
  •  We can write custom serialize or deserialize

if you don't have access of source code to serialize or deserialize a 3rd party POJO. What would you do? Also, you can open and clean to other JSON library, such as GSON

What is the solution to decoupled your code from Jackson annotation?

We can resolve this kind of problems by Jackson mix-in annotations. We can use in mix-in class or interface these type annotation but when we use a function as if they were directly included in the target class.

This blog will help you how to use the Jackson mix-in annotations.

Application Example?

Now we creating a simple Spring application to understand how Jackson mix-in annotation works.

Consider if you want to serialize or deserialize a User POJO in a Spring application.

Here is the code of POJO class which name is User.java

package guru.springframework.blog.domain;

public class User {
    private long id;
    private String name;
    private int age;
    private String gender;
    private String email;
    private String phoneNo;

    public User(long id, String name, int age, String gender, String email, String phoneNo) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.email = email;
        this.phoneNo = phoneNo;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                ", email='" + email + '\'' +
                ", phoneNo=" + phoneNo +
                '}';
    }
}

constructor and nor any getter and setter methods.

if you don't have any access to the source code of the User POJO or there is some constraint disallowing you to modify the existing POJO. In this scheme, you can’t serialize or deserialize a User object through annotations. 

Let us we try how mix-in annotations can solve this problem.

Jackson Mix-in Class

For Use Jackson mix-in annotation, First, you have to need to define a mix-in class on the interface for Jackson Mix-in Class.

Now define an abstract mix-in class for User. Confirm mix-in class has a constructor matching with the source POJO.

Now Use the @JsonCreator annotation and @JsonProperty property in UserMixin class. @JsonProperty property specify all the properties of the POJO.

Here is code for the UserMixin Jackson mix-in class.

UserMixin.class

Java

package guru.springframework.blog.mixin;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public abstract class UserMixin {
    @JsonCreator
    public UserMixin(@JsonProperty Long id, @JsonProperty String name,
                     @JsonProperty int age, @JsonProperty String gender,
                     @JsonProperty String email, @JsonProperty String phoneNo) {

    }
}

UserMixin is an abstract class. these constructors of the class are annotated with @JsonCreator to tell Jackson in what order to pass fields from a JSON object to the constructor.

Each parameter of the constructors are annotated with @JsonProperty property to specify all the properties to bind to.

When you create UserMixin.class then you must configure the ObjectMapper to use the mix-in for the User POJO, like this.

. . .
objectMapper.addMixIn(User.class, UserMixin.class);
String json = objectMapper.writerWithDefaultPrettyPrinter()
               .writeValueAsString(user);
. . .

Here is the complete test code of the Jackson mix-in:

UserSample.java

Java

package guru.springframework.blog.domain;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import guru.springframework.blog.mixin.UserMixin;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

public class UserSample {
    private User user;

    @Before
    public void setUp(){
        user = new User(123,"James",23,"Male",
                "[email protected]", "1234567890");
    }
    @After
    public void tearDown(){
        user = null;
    }

    @Test
    public void JacksonMixinAnnotationTest() throws JsonProcessingException{
        ObjectMapper objectMapper = buildMapper();
        objectMapper.addMixIn(User.class, UserMixin.class);
        String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);
        System.out.println(json);

    }

    private static ObjectMapper buildMapper(){
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibilityChecker(objectMapper.getSerializationConfig()
                .getDefaultVisibilityChecker()
                .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
                .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
        return objectMapper;
    }

}

Here is the output of the Jackson Mix-in:

 


About Author

Arun Singh

Arun is a MEAN stack developer. He has a fastest and efficient way of problem solving techniques. He is very good in JavaScript and also have a little bit knowledge of Java and Python.

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us