我正在轉換我的應用程式以擺脫 spring-boot,它現在只使用 Spring (5.3)。
我已經添加了@EnableWebMvc配置,并且我的端點大部分都可以正常作業 - 它們將我想要的資料作為 JSON 回傳。
之前,我使用 spring-boot 屬性自定義了日期格式:spring.jackson.date-format=yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
不過,在新的純彈簧應用程式中,它回歸到序列化為一個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.jackson.date-format純 Spring@EnableWebMvc設定相當于什么?
uj5u.com熱心網友回復:
您可以MappingJackson2HttpMessageConverter使用WebMvcConfigurerwith進行自定義@EnableWebMvc。
例如:
@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。訊息轉換器 - Servlet 堆疊上的 Web - docs.spring.io。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/441891.html
