gpt4 book ai didi

java - 使用 java-configuration 配置 MappingJackson2HttpMessageConverter

转载 作者:行者123 更新时间:2023-12-01 12:57:29 24 4
gpt4 key购买 nike

我正在尝试配置 MappingJackson2HttpMessageConverter,因为我想禁用 WRITE_DATES_TO_TIMESTAMP 功能。

如果我通过 xml-configuration 配置它,它会成功运行

<bean name="jacksonObjectMapper"
class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="featuresToDisable">
<array>
<util:constant
static-field="com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS" />
</array>
</property>
</bean>
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="jacksonObjectMapper" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>

但是当我尝试通过 java-configuration 进行配置时,转换器已注册但序列化忽略了映射器的配置。

我尝试了不同的方法。

方法一
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
ObjectMapper mapper = new ObjectMapper();
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
converters.add(new MappingJackson2HttpMessageConverter(mapper));
}
}

方法二
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
for (HttpMessageConverter<?> converter : converters) {
if (converter instanceof MappingJackson2HttpMessageConverter) {
MappingJackson2HttpMessageConverter jacksonMessageConverter = (MappingJackson2HttpMessageConverter) converter;
ObjectMapper objectMapper = jacksonMessageConverter.getObjectMapper();
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
break;
}
}
}

}

最佳答案

尝试以下方法:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

...
@Override
public void configureMessageConverters(
List<HttpMessageConverter<?>> converters) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.dateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm"));
builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
}
...
}

关于java - 使用 java-configuration 配置 MappingJackson2HttpMessageConverter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36906877/

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