Search code examples
spring-bootjacksongsonjackson2

How to change Jackson to detect all fields in a POJO, other than only public ones?


When using Spring Boot for a project, Jackson came as default to serialize objects back and from Jsons. I realize that Jackson fails if you don't have public accessors, e.g., getters/setters, or public fields in your POJO.

The behavior is different when I switch to Gson. It detects all fields regardless of their visibility. For this reason, I ended up using Gson.

I felt a little uncomfortable about switching my POJO access rules; It would force some refactoring in the project structure.

So, no problems using Gson, but is there a way of change Jackson's behavior?


Solution

  • Jackson does support reading values from private member fields, but does not do it by default.

    You can configure the behavior globally in the Spring Boot config like

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

    (this config will only look for member fields and no longer check get, set and is methods)

    You could also use the @JsonAutoDetect annotation to do the same setting for a specific class.