Java Jackson @JsonGetter Example

1. Introduction

Jackson's @JsonGetter annotation is used to mark a method as a getter method during serialization. By default, Jackson identifies public getter methods and serializes them into JSON. With @JsonGetter, you can specify a custom name for the JSON property, different from the method name.

2. Example Steps

1. Create a Person class with a few private fields.

2. Use @JsonGetter to annotate the getter method and provide a custom JSON property name.

3. Serialize an instance of the Person class and observe the output.

3. Java Jackson @JsonGetter Example

import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonJsonGetterExample {

    public static void main(String[] args) throws Exception {
        // Initialize ObjectMapper
        ObjectMapper mapper = new ObjectMapper();

        // Create a Person instance
        Person person = new Person("John", "Doe");

        // Serialize the Person instance
        String serializedPerson = mapper.writeValueAsString(person);

        // Print the serialized Person
        System.out.println(serializedPerson);
    }

    static class Person {
        private String firstName;
        private String lastName;

        public Person(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        @JsonGetter("name")
        public String getFullName() {
            return firstName + " " + lastName;
        }

        // Other getters and setters omitted for brevity
    }
}

Output:

{"name":"John Doe"}

4. Step By Step Explanation

The Person class contains a getFullName method that concatenates the first name and last name. By using the @JsonGetter annotation and specifying "name" as its value, we indicate that the JSON property name should be "name" instead of the default "fullName". As seen in the output, the JSON representation contains the "name" property with the full name of the person.


Comments