如何自訂Spring的ObjectMapper以僅序列化@JsonProperty註解的屬性?
Dec 04, 2024 am 06:16 AM在 Spring 中設定 ObjectMapper
在 Spring 應用程式中,ObjectMapper 是序列化和反序列化 JSON 資料的關鍵元件。您可以自訂 ObjectMapper 以滿足特定要求,例如僅序列化使用 @JsonProperty 註解的屬性。
要實現此目的,第一步是建立一個自訂 ObjectMapper 類,該類別擴展 Jackson 提供的基本 ObjectMapper 類別。覆寫預設的可見性檢查器以排除未註解的屬性:
public class MyCustomObjectMapper extends ObjectMapper { public MyCustomObjectMapper() { super(); setVisibilityChecker(getSerializationConfig() .getDefaultVisibilityChecker() .withCreatorVisibility(JsonAutoDetect.Visibility.NONE) .withFieldVisibility(JsonAutoDetect.Visibility.NONE) .withGetterVisibility(JsonAutoDetect.Visibility.NONE) .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE) .withSetterVisibility(JsonAutoDetect.Visibility.DEFAULT)); } }
接下來,在Spring 設定檔(servlet.xml)中註冊自訂ObjectMapper bean:
<bean>
最後,配置註解驅動的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="customObjectMapper" /> </bean> </list> </property> </bean>
在提供的範例程式碼中,NumbersOfNewEvents 類別包含兩個公用屬性:
public class NumbersOfNewEvents implements StatusAttribute { public Integer newAccepts; public Integer openRequests; // ... }
但是,只有newAccepts 屬性使用@JsonProperty 屬性:
@JsonProperty public Integer newAccepts;
透過如上所述配置ObjectMapper,只有newAccepts 屬性當NumbersOfNewEvents 物件轉換為 JSON 時應進行序列化。這是因為自訂 ObjectMapper 在序列化過程中會排除未註解的屬性。
以上是如何自訂Spring的ObjectMapper以僅序列化@JsonProperty註解的屬性?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱門文章

熱門文章

熱門文章標籤

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

2025年的前4個JavaScript框架:React,Angular,Vue,Svelte

如何將Maven或Gradle用於高級Java項目管理,構建自動化和依賴性解決方案?

Spring Boot Snakeyaml 2.0 CVE-2022-1471問題已修復

如何將JPA(Java持久性API)用於具有高級功能(例如緩存和懶惰加載)的對象相關映射?
