gpt4 book ai didi

java - 在 Spring 中配置 ObjectMapper

转载 作者:IT老高 更新时间:2023-10-28 12:43:28 33 4
gpt4 key购买 nike

我的目标是配置 objectMapper,使其仅序列化带有 @JsonProperty 注释的元素。

为了做到这一点,我遵循了 explanation其中说明了如何配置 objectmapper。

我包含了自定义对象映射器,如 here 所述.

但是,当类 NumbersOfNewEvents 被序列化时,它仍然包含 json 中的所有属性。

有人有提示吗?提前致谢

jackson 1.8.0 Spring 3.0.5

CustomObjectMapper

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

servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<context:component-scan base-package="de.Company.backend.web" />

<mvc:annotation-driven />

<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>

<bean id="jacksonObjectMapper" class="de.Company.backend.web.CompanyObjectMapper" />
</beans>

NumbersOfNewEvents

public class NumbersOfNewEvents implements StatusAttribute {

public Integer newAccepts;
public Integer openRequests;

public NumbersOfNewEvents() {
super();
}
}

最佳答案

使用 Spring Boot (1.2.4) 和 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;
}
}

关于java - 在 Spring 中配置 ObjectMapper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7854030/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com