Wednesday, April 3, 2019

Part II : Jackson Mix-ins, De/serializing third party objects with better control


Hello Friends, Welcome to my blog. Today in this blog we will be talking on Jackson Mix-ins feature, which allows us to have better control over the serialization of third party classes in which we cannot add our Jackson annotations.

Let's look at below example, Here we are using the Exception class from the java.lang package and we wanted to use this class to represent error object in our application. We will be storing this in our database.

public class JacksonMixInDemo {
 public static void main(String args[]) {
  ObjectMapper mapper = new ObjectMapper();
  mapper.enable(SerializationFeature.INDENT_OUTPUT);

  Exception ex = new Exception("Unable to Perform Operations");
  try {
   String jsonRep = mapper.writeValueAsString(ex);
   System.out.println("Third Party Object Representation : ");
   System.out.println(jsonRep);
  } catch (JsonProcessingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}
Output :
Third Party Object Representation : 
{
  "cause" : null,
  "stackTrace" : [ {
    "methodName" : "main",
    "fileName" : "JacksonMixInDemo.java",
    "lineNumber" : 16,
    "className" : "blog.javahotfix.jacksondemo.application.JacksonMixInDemo",
    "nativeMethod" : false
  } ],
  "localizedMessage" : "Unable to Perform Operations",
  "message" : "Unable to Perform Operations",
  "suppressed" : [ ]
}


If you observe the output of the above program, you might see the stack trace & suppressed attribute that you don't want in your serialized JSON representation.

How will you do it?

Once Option could be write wrapper around the Exception class or write a custom parser which will take out unwanted fields. But this will be the overhead to maintain those code. So in this situation, we can use the Jackson mix-in feature, which allows us to control the visibility of the fields in serialized JSON representation.

Let's take a look at below example which shows how can we ignore the unwanted filed from JSON using Jackson mix-in feature.

  1. Create the abstract class or interface which is known as a mix-in class 
  2. Add the Getter for the fields which you don't want in your JSON representation
  3. Add JSON Ignore annotation over them
  4. Configure the ObjectMapper instance to know for which third-party class we have a mix-in class in our code base. This can be done using addMixIn Method by passing Source class & Mix-in class.

Let's take a look at the above steps in action.
package blog.javahotfix.jacksondemo.application;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JacksonMixInDemo {
 public static void main(String args[]) {
  
  ObjectMapper mapper = new ObjectMapper();
  mapper.enable(SerializationFeature.INDENT_OUTPUT);
  // You can use Abstract class or Interface eighter of them
  mapper.addMixIn(Exception.class, ExceptionMixIns.class);
 //mapper.addMixIn(Exception.class, ExceptionMixIn2.class);
  
  Exception ex = new Exception("Unable to Perform Operations");
  
  try {
   String jsonRep = mapper.writeValueAsString(ex);
   System.out.println("Third Party Object Representation : ");
   System.out.println(jsonRep);
  } catch (JsonProcessingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

abstract class ExceptionMixIns {
 @JsonIgnore
 public abstract Object getStackTrace();
 
 @JsonIgnore
 public abstract Object getSuppressed();
}

interface ExceptionMixIn2 {
 @JsonIgnore
 public abstract Object getStackTrace();
 
 @JsonIgnore
 public Object getSuppressed();
}

Output :
Third Party Object Representation : 
{
  "cause" : null,
  "localizedMessage" : "Unable to Perform Operations",
  "message" : "Unable to Perform Operations"
}

I hope you have understood this Jackson mix-in feature. You can have much cleaner code with using this feature. And the code will be easily portable to another JSON processing library.


That's all for this blog friends if you have any queries, concern or feedback please let us know in comment box below till then

Good Bye !!! Happy Coding !!!

0 comments:

Post a Comment