Home >Java >javaTutorial >How to Configure ObjectMapper in Spring for Custom JSON Serialization and Deserialization?
In Spring, the ObjectMapper can be configured to suit specific requirements. This is particularly useful when you want to control the serialization and deserialization behavior of your JSON data.
One common scenario is to exclude certain properties from serialization unless they are explicitly annotated. To achieve this, we follow these steps:
Create a custom ObjectMapper:
public class CompanyObjectMapper extends ObjectMapper { public CompanyObjectMapper() { super(); setVisibilityChecker(getSerializationConfig() .getDefaultVisibilityChecker() .withCreatorVisibility(JsonAutoDetect.Visibility.NONE) .withFieldVisibility(JsonAutoDetect.Visibility.NONE) .withGetterVisibility(JsonAutoDetect.Visibility.NONE) .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE) .withSetterVisibility(JsonAutoDetect.Visibility.DEFAULT)); } }
Include the custom ObjectMapper in Spring's configuration:
<bean>
Configure Spring MVC to use the custom ObjectMapper:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="objectMapper" ref="jacksonObjectMapper" /> </bean> </list> </property> </bean>
However, this approach may not work as expected if you are using Spring versions 3.0.5 and Jackson 1.8.0. To resolve this issue, it is recommended to use the following annotation-based configuration with Spring Boot and Jackson 2.4.6 or newer:
@Configuration public class JacksonConfiguration { @Bean public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true); return mapper; } }
This configuration will enable the ObjectMapper to only serialize properties that have the @JsonProperty annotation, satisfying the desired requirement.
The above is the detailed content of How to Configure ObjectMapper in Spring for Custom JSON Serialization and Deserialization?. For more information, please follow other related articles on the PHP Chinese website!