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

前端 未结 3 1198
悲哀的现实
悲哀的现实 2020-12-04 13:39

I want to serialize and deserialize an immutable object using com.fasterxml.jackson.databind.ObjectMapper.

The immutable class looks like this (just 3 internal attr

相关标签:
3条回答
  • 2020-12-04 14:26

    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.

    0 讨论(0)
  • 2020-12-04 14:31

    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;
    }
    
    0 讨论(0)
  • 2020-12-04 14:34

    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"
    }
    
    0 讨论(0)
提交回复
热议问题