Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to de/serialize an immutable object without default constructor using ObjectMapper?

Tags:

java

json

To let Jackson know how to create an object for deserialization, use the @JsonCreator and @JsonProperty annotations for your constructors, like this:

@JsonCreator
public ImportResultItemImpl(@JsonProperty("name") String name, 
        @JsonProperty("resultType") ImportResultItemType resultType, 
        @JsonProperty("message") String message) {
    super();
    this.resultType = resultType;
    this.message = message;
    this.name = name;
}

You can use a private default constructor, Jackson will then fill the fields via reflection even if they are private final.

EDIT: And use a protected/package-protected default constructor for parent classes if you have inheritance.


The first answer of Sergei Petunin is right. However, we could simplify code with removing redundant @JsonProperty annotations on each parameter of constructor.

It can be done with adding com.fasterxml.jackson.module.paramnames.ParameterNamesModule into ObjectMapper:

new ObjectMapper()
        .registerModule(new ParameterNamesModule(JsonCreator.Mode.PROPERTIES))

(Btw: this module is registered by default in SpringBoot. If you use ObjectMapper bean from JacksonObjectMapperConfiguration or if you create your own ObjectMapper with bean Jackson2ObjectMapperBuilder then you can skip manual registration of the module)

For example:

public class FieldValidationError {
  private final String field;
  private final String error;

  @JsonCreator
  public FieldValidationError(String field,
                              String error) {
    this.field = field;
    this.error = error;
  }

  public String getField() {
    return field;
  }

  public String getError() {
    return error;
  }
}

and ObjectMapper deserializes this json without any errors:

{
  "field": "email",
  "error": "some text"
}

It's 2021, I had the same issue. Unfortunately, the previous answers in this thread weren't helpful in my case, because:

  1. I need to deserialize java.net.HttpCookie class object. I can't modify it.
  2. Due to some reasons, I use jackson-databind-2.11.0 version. ParameterNamesModule has been added in 3+ version.

So, here's the solution I've found for my case. You can just use DeserializationProblemHandler:

    objectMapper.addHandler(new DeserializationProblemHandler() {


        @Override
        public Object handleMissingInstantiator(DeserializationContext ctxt, Class<?> instClass, ValueInstantiator valueInsta, JsonParser p, String msg) throws IOException {
            return super.handleMissingInstantiator(ctxt, instClass, valueInsta, p, msg);
        }

    });

Just return the object which you're expecting