Configuring ObjectMapper in Spring: Restrict Field Serialization
To configure the ObjectMapper to serialize only fields annotated with @JsonProperty, consider the following approach:
1. Create a Custom ObjectMapper
public class CustomObjectMapper extends ObjectMapper { public CustomObjectMapper() { super(); setVisibility(Visibility.NONE).enable(Visibility.NON_EMPTY); } }
This custom ObjectMapper disables serialization of non-annotated fields and only includes fields where the value is non-null.
2. Register the Custom ObjectMapper in Spring
In your servlet.xml, register the custom ObjectMapper as follows:
<bean>
3. Update Annotation-Based Configuration
Ensure that your @Configuration class registers the custom CountingJacksonHttpMessageConverter:
@Configuration public class JacksonConfiguration { @Bean public MappingJacksonHttpMessageConverter jsonConverter() { MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter(); converter.setObjectMapper(jacksonObjectMapper()); return converter; } }
4. Ensure Proper Version Dependency
Verify that you are using a compatible version of Jackson. In this case, Jackson 2.x is recommended for use with Spring.
5. Verify Exclude Default Jackson Annotations
Ensure that the default Jackson annotations are excluded from visibility detection by overriding the setVisibility method in your custom ObjectMapper.
Additional Considerations:
The above is the detailed content of How to Configure Spring's ObjectMapper to Serialize Only @JsonProperty Annotated Fields?. For more information, please follow other related articles on the PHP Chinese website!