首页 >Java >java教程 >如何在 Spring 中配置 ObjectMapper 进行自定义 JSON 序列化和反序列化?

如何在 Spring 中配置 ObjectMapper 进行自定义 JSON 序列化和反序列化?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-12-05 07:15:16859浏览

How to Configure ObjectMapper in Spring for Custom JSON Serialization and Deserialization?

在 Spring 中配置 ObjectMapper

在 Spring 中,可以配置 ObjectMapper 以满足特定需求。当您想要控制 JSON 数据的序列化和反序列化行为时,这特别有用。

一种常见的情况是从序列化中排除某些属性,除非它们被显式注释。为此,我们按照以下步骤操作:

  1. 创建自定义 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));
        }
    }
  2. 在 Spring 中包含自定义 ObjectMapper配置:

    <bean>
  3. 配置 Spring MVC 使用自定义 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>

但是,如果您使用 Spring 版本 3.0.5 和 Jackson,此方法可能无法按预期工作1.8.0。要解决此问题,建议在 Spring Boot 和 Jackson 2.4.6 或更高版本中使用以下基于注释的配置:

@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;
    }
}

此配置将使 ObjectMapper 仅序列化具有 @ 的属性JsonProperty注解,满足需求。

以上是如何在 Spring 中配置 ObjectMapper 进行自定义 JSON 序列化和反序列化?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn