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

前端 未结 3 1203
悲哀的现实
悲哀的现实 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条回答
  •  猫巷女王i
    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"
    }
    

提交回复
热议问题