- Details
- Written by Nam Ha Minh
- Last Updated on 28 October 2023   |   Print Email
In this short post, I’d like to share with you how to use the
@JsonProperty annotation provided by FasterXML/Jackson - the Java JSON library - to set custom name/logical name of properties present in the JSON document in response body.The
@JsonProperty annotation can be used at both field level and method level, and it has some optional parameters.Consider the following DTO class:
public class LocationDTO {
private String code;
private String cityName;
private String regionName;
private String countryName;
private String countryCode;
private boolean enabled;
// getters and setters are not shown for brevity
}
By default, the field names will be property names in the JSON object. So a GET API call will produce the following JSON:
{
"code": "NYC_USA",
"enabled": true,
"cityName": "New York City",
"regionName": "New York",
"countryName": "United States of America",
"countryCode": "US"
}
What if we want to have the property names
city_name instead of
cityName,
region_name instead of
regionName, and similar for the fields
countryName and
countryCode? In a Java/Spring project that uses Jackson library, we can use the
@JsonProperty annotation like this:
@JsonProperty("city_name")
private String cityName;
So let’s update the DTO class above:
public class LocationDTO {
private String code;
@JsonProperty("city_name")
private String cityName;
@JsonProperty("region_name")
private String regionName;
@JsonProperty("country_name")
private String countryName;
@JsonProperty("country_code")
private String countryCode;
private boolean enabled;
// getters and setters are not shown for brevity
}
Hence the following output:
{
"code": "NYC_USA",
"city_name": "New York City",
"region_name": "New York",
"country_code": "US",
"country_name": "United States of America",
"enabled": true
}
You can also use the
@JsonProperty annotation at method level - getter and setter both work. For example:
@JsonProperty("city_name")
public String getCityName() {
return cityName;
}
@JsonProperty("region_name")
public void setRegionName(String regionName) {
this.regionName = regionName;
}
Those are some examples of using
@JsonProperty annotation to set JSON custom property name in Java/Spring project using Jackson library. To learn more about this annotation, check the Javadocs link below.
Also watch the video below to see how I use the
@JsonProperty annotation in a real life project:
Reference:
Annotation Type JsonProperty
Related REST API Tutorials:
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on
Facebook and watch
his Java videos on YouTube.