1. Overview

In this tutorial, we'll look at how Jackson sets property values during deserialization.

For example, we'll investigate whether Jackson uses the field or the method during deserialization. We've covered a similar topic for serialization.

We'll see that if the class has only fields and visibility conditions are met, Jackson uses fields. If the class has both fields and methods with appropriate visibility levels, Jackson uses methods values.

2. Only fields

Firstly, we'll investigate the case where we have only fields without setter methods.

We have the Person class:

public class Person {

    public int age;
}

It has one public field, age.

During deserialization, Jackson sets the age field with the value from the JSON string. Since we don't have any setter method, Jackson achieves this reflectively.

@Test
public void shouldDeserialize() throws IOException {
    final String json = "{\"age\":12}";

    Person deserialized = objectMapper.readValue(json, Person.class);

    assertThat(deserialized.age).isEqualTo(12);
}

3. Fields and Methods

Secondly, let's look at the case where we have both fields and setter methods.

We have the PersonWithSetter class:

public class PersonWithSetter {

    public int age;

    public void setAge(int age) {
        this.age = 999;
    }
}

This class has a setter method. However, this setter method ignores the method argument. It always sets the age field with 999 regardless of the method argument.

During deserialization, Jackson uses the setter method, so the age field gets the value of 999.

@Test
public void shouldDeserialize_WithSetter() throws IOException {
    final String json = "{\"age\":12}";

    PersonWithSetter deserialized = objectMapper.readValue(json, PersonWithSetter.class);

    assertThat(deserialized.age).isEqualTo(999);
}

4. Summary

In this tutorial, we've investigated how Jackson sets property values during deserialization.

Check out the source code for all examples over on Github.