JsonProperty
isn\'t overriding the default name jackson gets from the getter. If I serialize the class below with ObjectMapper
and jackson I get
I had this problem when updating from older version to 2.8.3 of FasterXML Jackson.
The issue was when deserializing the JSON response from our DB into Java class object, our code didn't have @JsonSetter
on the class' setters. Hence, when serializing, the output wasn't utilizing the class' getters to serialize the Java class object into JSON (hence the @JsonProperty()
decorator wasn't taking effect).
I fixed the issue by adding @JsonSetter("name-from-db")
to the setter method for that property.
Also, instead of @JsonProperty()
, to rename properties using the getter method, you can and should use @JsonGetter()
which is more specific to renaming properties.
Here's our code:
public class KwdGroup {
private String kwdGroupType;
// Return "type" instead of "kwd-group-type" in REST API response
@JsonGetter("type") // Can use @JsonProperty("type") as well
public String getKwdGroupType() {
return kwdTypeMap.get(kwdGroupType);
}
@JsonSetter("kwd-group-type") // "kwd-group-type" is what JSON from the DB API outputs for code to consume
public void setKwdGroupType(String kwdGroupType) {
this.kwdGroupType = kwdGroupType;
}
}