JsonProperty
isn\'t overriding the default name jackson gets from the getter. If I serialize the class below with ObjectMapper
and jackson I get
Have you tried below
class JacksonTester {
private String hi;
@JsonProperty("hello")
public String getHi() {
return hi;
}
}
I mean making the 'hi' variable declaration as private. Alternatively try to put a @JsonIgnore on the variable declaration and in case you would rather keep it at default scope.
If using Kotlin
I understand the original question is in Java, but since Kotlin is becoming very popular and many might be using it I'd like to post this here to help others.
Anyway, for Kotlin, because how getters/setters work, if you are using val
, meaning you only expose the getter, you may need to apply the annotation to the getter like below:
class JacksonTester(@get:JsonProperty("hello") val hi: String)
Place it on the variable, not the getter
class JacksonTester {
@JsonProperty("hello")
private String hi;
public String getHi() {
return hi;
}
}
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;
}
}