为 spring-mvc(非引导)自定义 JSON JSON 的日期格式?
Customise JSON date formatting of JSON for spring-mvc (non-boot)?
我正在转换我的应用程序以摆脱 spring-boot,它现在只使用 Spring (5.3)。
我已经添加了 @EnableWebMvc
配置,并且我的端点大部分都正常工作 - 它们 return 我想要的数据 JSON。
之前,我使用 spring-boot 属性 自定义了日期格式:spring.jackson.date-format=yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
虽然在新的纯 spring 应用程序中,它回归序列化为 long
值。
我尝试了以下方法,但它似乎根本没有使用这些 bean:
@Bean
public ObjectMapper objectMapper() {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
ObjectMapper dateFormatMapper = new ObjectMapper();
dateFormatMapper.setDateFormat(dateFormat);
return dateFormatMapper;
}
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2JsonView(){
var converter = new MappingJackson2HttpMessageConverter();
converter.getObjectMapper().setDateFormat(
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") );
return converter;
}
我希望在全局范围内自定义格式,而不是在每个字段的基础上。
纯 Spring @EnableWebMvc
设置的 spring.jackson.date-format
相当于什么?
您可以通过将 WebMvcConfigurer
与 @EnableWebMvc
结合使用来自定义 MappingJackson2HttpMessageConverter
。
例如:
@Configuration
@EnableWebMvc
public class YourConfiguration implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
.indentOutput(true)
.dateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
}
}
更多信息,请参阅1.11.7. Message Converters - Web on Servlet Stack - docs.spring.io。
我正在转换我的应用程序以摆脱 spring-boot,它现在只使用 Spring (5.3)。
我已经添加了 @EnableWebMvc
配置,并且我的端点大部分都正常工作 - 它们 return 我想要的数据 JSON。
之前,我使用 spring-boot 属性 自定义了日期格式:spring.jackson.date-format=yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
虽然在新的纯 spring 应用程序中,它回归序列化为 long
值。
我尝试了以下方法,但它似乎根本没有使用这些 bean:
@Bean
public ObjectMapper objectMapper() {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
ObjectMapper dateFormatMapper = new ObjectMapper();
dateFormatMapper.setDateFormat(dateFormat);
return dateFormatMapper;
}
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2JsonView(){
var converter = new MappingJackson2HttpMessageConverter();
converter.getObjectMapper().setDateFormat(
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") );
return converter;
}
我希望在全局范围内自定义格式,而不是在每个字段的基础上。
纯 Spring @EnableWebMvc
设置的 spring.jackson.date-format
相当于什么?
您可以通过将 WebMvcConfigurer
与 @EnableWebMvc
结合使用来自定义 MappingJackson2HttpMessageConverter
。
例如:
@Configuration
@EnableWebMvc
public class YourConfiguration implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
.indentOutput(true)
.dateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
}
}
更多信息,请参阅1.11.7. Message Converters - Web on Servlet Stack - docs.spring.io。