Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does jackson set private properties without setters?

Tags:

java

json

jackson

I am very curious how Jackson creates objects including it's private properties/fields without setters and just using the objects empty constructor.

The reason I'm asking is that when I de-serialize certain properties I want to automatically set other properties based on these values. For example, I would not want to serialize an image but just it's path. Once the path is de-serialized the @JsonIgnore field Image can load the actual image. After the construction of the deserialized object the fields have not yet been assigned. And the getters are logically not being called. So what voodoo magic is touching my objects private parts?

public class ItemTemplate {

    private String imagePath;

    public ItemTemplate() {
        System.out.println(imagePath); //Still null
    }

    public String getImagePath() {
        System.out.println(imagePath); //Not being called when deserializing.
        return imagePath;
    }
}

But when Jackson is done de-serializing this object it has it's imagePath set.

like image 886
Madmenyo Avatar asked May 06 '17 13:05

Madmenyo


Video Answer


1 Answers

The first comment answered the question in the title. Jackson uses reflection to access private and protected properties. This somehow led me to trying out a private setter for the imagePath field. This setter does get used by Jackson instead of directly accessing the field. Within this setter I could set the actual image using the path string and still remain private.

like image 163
Madmenyo Avatar answered Sep 17 '22 13:09

Madmenyo