1. Overview

In this tutorial, we'll look at how Jackson retrieves property values during serialization.

For example, we'll investigate whether Jackson uses the field value or the getter method value when we serialize an object.

2. Serialization with Only Fields

Let's start with the case where we have only fields without the getter methods.

By default, Jackson needs instance fields to be public in order to access them. Although we can configure this behavior, we'll just handle the default case for this tutorial.

So we have the Person class:

@Test
public void shouldSerialize_PublicFields() throws JsonProcessingException {

    class Person {

        public int age = 12;
    }

    Person person = new Person();

    String json = objectMapper.writeValueAsString(person);

    assertThat(json).isEqualTo("{\"age\":12}");
}

Here, Person has only the age field. Since it is public, visibility conditions are met. Consequently, Jackson uses the field value during serialization.

3. Serialization with Fields and Methods

Now let's continue with the case where we have both fields and getter methods.

When the class has a getter method for a field, Jackson prefers the getter method to the field during serialization:

@Test
public void shouldSerialize_PublicFields_WithPrioritizingGetter() throws JsonProcessingException {

    class Person {

        public int age = 12;

        public int getAge() {
            return 999;
        }
    }

    Person person = new Person();

    String json = objectMapper.writeValueAsString(person);

    assertThat(json).isEqualTo("{\"age\":999}");
}

Here, we have a Person class with age field. Note that we also have a getter method. So Jackson will use the getter method and will serialize age as 999 instead of 12.

4. Summary

In this tutorial, we've investigated how Jackson retrieves a property value during serialization.

Finally, we concluded that if the class has only fields and visibility conditions are met, Jackson uses fields.

On the other hand, if the class has both fields and methods with appropriate visibility levels, Jackson uses method values.

Check out the source code over on Github.