Course – LS (cat=JSON/Jackson)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

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.

2. Change Name of Field for Serialization

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"));
}

3. Conclusion

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.

The implementation of all these examples and code snippets can be found in my github project.

Course – LS (cat=JSON/Jackson)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – Jackson (eBook) (cat=Jackson)
Comments are closed on this article!