在 Spring 中,可以設定 ObjectMapper 以符合特定需求。當您想要控制 JSON 資料的序列化和反序列化行為時,這特別有用。
一個常見的情況是從序列化中排除某些屬性,除非它們被明確註釋。為此,我們按照以下步驟操作:
建立自訂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)); } }
<bean>
<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 中配置 ObjectMapper 進行自訂 JSON 序列化和反序列化?的詳細內容。更多資訊請關注PHP中文網其他相關文章!