我正在尝试配置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配置进行配置时,转换器已注册,但序列化忽略了映射器的配置。
我尝试了不同的方法。
方法1
@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));
}
}
方法2
@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;
}
}
}
}
答案 0 :(得分:4)
尝试以下方法:
@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()));
}
...
}
答案 1 :(得分:0)
这对我也有用
@Bean
public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return builder;
}
答案 2 :(得分:0)
也许你仍然在xml中有注释驱动?
还注册了默认的messageConverters和objectmappers。