I just announced the new Spring 5 modules in REST With Spring:

>> 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 – strValue, we need to simply annotate the getter:

@JsonProperty("strVal")
public String getStringValue() {
    return stringValue;
}

Now, on serialization, we will get the desired output:

{"strValue":"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

Marhalling 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 – this is an Eclipse based project, so it should be easy to import and run as it is.

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE LESSONS