How to specify jackson to only use fields - preferably globally

前端 未结 8 526
旧巷少年郎
旧巷少年郎 2020-11-22 17:03

Default jackon behaviour seems to use both properties (getters and setters) and fields to serialize and deserialize to json.

I would like to use the fields as the ca

相关标签:
8条回答
  • 2020-11-22 17:57

    In Jackson 2.0 and later you can simply use:

    import com.fasterxml.jackson.annotation.JsonAutoDetect;
    import com.fasterxml.jackson.annotation.PropertyAccessor;
    import com.fasterxml.jackson.databind.ObjectMapper;   
    
    ...
    
    ObjectMapper mapper = new ObjectMapper();    
    mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    

    to turn off autodetection.

    0 讨论(0)
  • 2020-11-22 17:57

    Specifically for boolean is*() getters:

    I've spend a lot of time on why neither below

      @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
    

    nor this

      setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE);
      setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE);
      setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    

    worked for my Boolean Getter/Setter.

    Solution is simple:

      @JsonAutoDetect(isGetterVisibility = Visibility.NONE, ...          
      setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE);
    

    UPDATE: spring-boot allowed configure it:

    jackson:
      visibility.field: any
      visibility.getter: none
      visibility.setter: none
      visibility.is-getter: none
    

    See Common application properties # JACKSON

    0 讨论(0)
提交回复
热议问题