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