Serialize only compile-time information

Markus Appel :

When serializing a Java object, because it utilizes reflection, Jackson serializes the object in it's runtime representation.

I have the following class:

@lombok.AllArgsConstructor
@lombokGetter
class ErrorInformation {

   private final Exception exception;
}

and

final ErrorInformation errorInfo = new ErrorInformation(new IllegalArgumentException("foo"));

Instead of just serializing an Exception, Jackson actually serializes all fields in an IllegalArgumentException - with uncontrollable consequences like cyclic references (see e.g. mostSpecificCause in org.springframework.web.client.HttpServerErrorException).

How can I tell Jackson to actually only serialize information of the Exception, with no regard of the actual runtime type, as you would expect from a statically typed language like Java?

Ashishkumar Singh :

Since we cannot change IllegalArgumentException class logic, you can create additional instance field in your ErrorInformation class, populate it with information that you want to serialize and mark the exception variable as transient

e.g. Let's say you want to save the error message information. So, create a String field say errorMessage and populate it with the error message information in the constructor. Below is a sample code.

@lombok.AllArgsConstructor
@lombokGetter
class ErrorInformation {

   private final transient Exception exception;
   private final String errorMessage ;
   ErrorInformation(Exception exp) {
    this.exception = exp;
    this.errorMessage = exp.getMessage();
    }

}

At the time of de-serialization, you can use this error message information to create a similar(not same) instance of exception object which was serialized

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=117549&siteId=1