首頁 > Java > java教程 > 如何在 Spring 中配置 ObjectMapper 進行自訂 JSON 序列化和反序列化?

如何在 Spring 中配置 ObjectMapper 進行自訂 JSON 序列化和反序列化?

Mary-Kate Olsen
發布: 2024-12-05 07:15:16
原創
864 人瀏覽過

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. <bean>
    登入後複製
  3. <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>
    登入後複製

@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;
    }
}
登入後複製

設定Spring MVC 使用自訂ObjectMapper:但是,如果您使用Spring 版本3.0.5 和Jackson,此方法可能無法如預期般運作1.8.0。要解決此問題,建議在Spring Boot 和Jackson 2.4.6 或更高版本中使用以下基於註釋的配置:此配置將使ObjectMapper 僅序列化具有@ 的屬性JsonProperty註解,滿足需求。

以上是如何在 Spring 中配置 ObjectMapper 進行自訂 JSON 序列化和反序列化?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板