
Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:
Once the early-adopter seats are all used, the price will go up and stay at $33/year.
Last updated: June 28, 2023
This quick tutorial illustrates how to change the name of a field to map to another JSON property on serialization.
If you want to dig deeper and learn other cool things you can do with the Jackson 2 – head on over to the main Jackson tutorial.
Working with a simple entity:
public class MyDto {
private String stringValue;
public MyDto() {
super();
}
public String getStringValue() {
return stringValue;
}
public void setStringValue(String stringValue) {
this.stringValue = stringValue;
}
}
Serializing it will result in the following JSON:
{"stringValue":"some value"}
To customize that output so that, instead of stringValue we get – for example – strVal, we need to simply annotate the getter:
@JsonProperty("strVal")
public String getStringValue() {
return stringValue;
}
Now, on serialization, we will get the desired output:
{"strVal":"some value"}
A simple unit test should verify the output is correct:
@Test
public void givenNameOfFieldIsChanged_whenSerializing_thenCorrect()
throws JsonParseException, IOException {
ObjectMapper mapper = new ObjectMapper();
MyDtoFieldNameChanged dtoObject = new MyDtoFieldNameChanged();
dtoObject.setStringValue("a");
String dtoAsString = mapper.writeValueAsString(dtoObject);
assertThat(dtoAsString, not(containsString("stringValue")));
assertThat(dtoAsString, containsString("strVal"));
}
Marshaling an entity to adhere to a specific JSON format is a common task – and this article shows how to do is simply by using the @JsonProperty annotation.