Change Field Names with @JsonProperty

In this article, we’ll delve into the versatility of Jackson’s @JsonProperty annotation, which allows you to customize field names during both serialization and deserialization.

Changing Field Names for Serialization

To change a field name during serialization, apply the @JsonProperty annotation to the field you want to customize:


public class Person {
    private Long id;

    @JsonProperty("full_name")
    private String name;

    @JsonProperty("birth_date")
    private String dateOfBirth;

    // Getters and setters (not shown for brevity)
}

In this example, we’ve annotated the “name” and “dateOfBirth” properties with @JsonProperty. During serialization, these properties will be mapped to “full_name” and “birth_date” in the resulting JSON.

    private static void serialize() throws JsonProcessingException {
        Person alice = new Person();
        alice.setId(1L);
        alice.setName("Alice");
        alice.setDateOfBirth("1990-05-15");

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(alice);
        System.out.println("Person object to JSON String: " + jsonString);
    }

Output:

Person object to JSON String: {"id":1,"full_name":"Alice","birth_date":"1990-05-15"}

Changing Field Names for Deserialization

@JsonProperty annotation also works for deserialization.

private static void deserialize() throws JsonProcessingException {
        String json = "{\"id\":1,\"full_name\":\"Alice\",\"birth_date\":\"1990-05-15\"}";
        ObjectMapper objectMapper = new ObjectMapper();
        Person person = objectMapper.readValue(json, Person.class);

        System.out.println("JSON String to Person object: " + person);
    }

Tht output:

JSON String to Person object: Person(id=1, name=Alice, dateOfBirth=1990-05-15)

Read More