How to specify jackson to only use fields - preferably globally
To specify Jackson to use only fields globally, apply the following configuration to an ObjectMapper
instance:
For a specific class, utilize @JsonAutoDetect to apply field visibility:
Diving deeper: Additional configurations
Global visibility with ObjectMapper's wrapper
To apply the settings globally, especially in larger applications with numerous ObjectMapper
instances, a viable strategy is to implement a wrapper around ObjectMapper:
Handling getters/setters and creators
Occasionally, you might need to handle boolean getters (is...
methods) too. Adjust their visibility this way:
Mixins for flexible field visibility
Mixins provide a powerful way to apply annotations without messing with existing class source codes. A global field visibility mixin looks like this:
Now, field visibility is globally set to ANY for every class visited by Jackson.
Tactical application: When and where
Classroom level teaching: Annotating specific classes
For certain classes, you may need to override the global rules. Use @JsonAutoDetect
at class-level:
Spring Boot configuration
If you're working with Spring Boot, you can externalize these settings:
This grants easy manageability across various environments.
Caveats and considerations
These methods allow efficient serialization, but are not universal solutions. Applications that require intricate JSON structure control, or maintaining backward compatibility, may require additional customizations.
Was this article helpful?