Why jackson is serializing transient member also?

£可爱£侵袭症+ 提交于 2019-12-20 09:59:42

问题


I am serializing a POJO into JSON using Jackson 2.1.4 but I want to ignore a particular field from getting serialized. I used transient but still it is serializing that element.

public class TestElement {

    int x;

    private transient String y;

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public String getY() {
        return y;
    }

    public void setY(String y) {
        this.y = y;
    }
}

I am serializing as following:

public static void main(String[] args) throws JsonProcessingException {
    TestElement testElement = new TestElement();
    testElement.setX(10);
    testElement.setY("adasd");
    ObjectMapper om = new ObjectMapper();
    String serialized = om.writeValueAsString(testElement);
    System.err.println(serialized);
}

Please don't suggest @JsonIgnore as I don't want to tie my model to jackson specific annotations. Can it be done using transient only? Is there any API on objectmapper for visibility settings?


回答1:


The reason Jackson serializes the transient member is because the getters are used to determine what to serialize, not the member itself - and since y has a public getter, that gets serialized. If you want to change that default and have Jackson use fields - simply do:

om.setVisibilityChecker(
om.getSerializationConfig().
getDefaultVisibilityChecker().
withFieldVisibility(JsonAutoDetect.Visibility.ANY).
withGetterVisibility(JsonAutoDetect.Visibility.NONE));

Another way to ignore a property on serialization is to do it directly on the class:

@JsonIgnoreProperties(value = { "y" })
public class TestElement {
...

And another way is directly on the field:

public class TestElement {

    @JsonIgnore
    private String y;
...

Hope this helps.




回答2:


A new way to stop Jackson from serializing and deserializing is to call mapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true).




回答3:


I can't make comments so complete the previous response here, changing the (now) deprecated method setVisibilityChecker and adding a missing clause for booleans:

mapper.setVisibility(
    mapper.getSerializationConfig().
    getDefaultVisibilityChecker().
    withFieldVisibility(JsonAutoDetect.Visibility.ANY).
    withGetterVisibility(JsonAutoDetect.Visibility.NONE).
    withIsGetterVisibility(JsonAutoDetect.Visibility.NONE)
);


来源:https://stackoverflow.com/questions/21745593/why-jackson-is-serializing-transient-member-also

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!