杰克逊如何在没有制定者的情况下设置私有财产?

时间:2022-10-11 18:04:20

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

我非常好奇杰克逊如何创建对象,包括它的私有属性/字段,没有setter,只使用对象空构造函数。

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?

我问的原因是当我反序列化某些属性时,我想根据这些值自动设置其他属性。例如,我不想序列化图像,只是它的路径。一旦路径被反序列化,@ JsonIgnore字段Image就可以加载实际图像。构建反序列化对象后,尚未分配字段。并且逻辑上没有调用getter。那么伏都教魔法是什么触摸我的物体私处?

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.

但是当杰克逊完成对这个对象的反序列化时,它就有了它的imagePath设置。

1 个解决方案

#1


5  

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.

第一条评论回答了标题中的问题。杰克逊使用反射访问私人和受保护的财产。这在某种程度上导致我为imagePath字段尝试私有的setter。这个二传手确实被杰克逊使用而不是直接访问该领域。在这个setter中,我可以使用路径字符串设置实际图像,但仍保持私有。

#1


5  

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.

第一条评论回答了标题中的问题。杰克逊使用反射访问私人和受保护的财产。这在某种程度上导致我为imagePath字段尝试私有的setter。这个二传手确实被杰克逊使用而不是直接访问该领域。在这个setter中,我可以使用路径字符串设置实际图像,但仍保持私有。