Jackson change json field name
Suppose there is a java class as below
public class Child { private String dateOfBirth; // getter and setter }
When an object of this class is serialized using Jackson ObjectMapper, the resulting json string will be
{"dateOfBirth": "11/11/2021"}
where keys of json string are the same as the properties of java class.
But, what we want is a response as below
{"dob": "11/11/2021"}
with keys of json string other than properties of the class.
In this article, we will understand how to do this in Jackson.
This annotation can be used to change the name of a property or field at serialization.
Required name can be written directly after the annotation or along with value attribute as shown below
import com.fasterxml.jackson.annotation.JsonProperty; public class Child { @JsonProperty("dob") private String dateOfBirth; // getter and setter }
Below declaration is also valid
@JsonProperty(value="dob") private String dateOfBirth;
Providing empty value with JsonInclude
means there will be no change in property during serialization.
Jackson docs state,
Default value (“”) indicates that the field name is used as the property name without any modifications, but it can be specified to non-empty value to specify different name.
@JsonProperty over getters
This annotation can also be applied over getter methods of properties as shown below
import com.fasterxml.jackson.annotation.JsonProperty; public class Child { private String dateOfBirth; @JsonProperty("dob") public String getDateOfBirth() { return dateOfBirth; } }
This can also be used with value
attribute.
Hope the article was useful.