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

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"
}

Tags:

Java

Json