Why jackson is serializing transient member also?

前端 未结 4 1662
花落未央
花落未央 2021-02-01 13:53

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.

相关标签:
4条回答
  • 2021-02-01 14:22

    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.

    0 讨论(0)
  • 2021-02-01 14:32

    You can configure it with springs properties

    spring.jackson.mapper.propagate-transient-marker=true
    
    0 讨论(0)
  • 2021-02-01 14:40

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

    0 讨论(0)
  • 2021-02-01 14:43

    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)
    );
    
    0 讨论(0)
提交回复
热议问题