方法:重写MessageConverter, 使得yyyy-MM-dd HH:mm:ss的字符串能反序列化到LocalDateTime类型上。
@Configuration
public class HttpClientConfig {
@Value("${service.host}")
private String host;
@Bean
RestClient.Builder restClientBuilder() {
return RestClient.builder();
}
@Bean
public HttpServiceProxyFactory httpServiceProxyFactory(RestClient.Builder restClientBuilder) {
HttpExchangeAdapter httpExchangeAdapter = RestClientAdapter.create(
restClientBuilder.baseUrl(host)
.messageConverters(httpMessageConverters -> {
httpMessageConverters.stream()
.filter(converter -> converter instanceof MappingJackson2HttpMessageConverter)
.map(converter -> (MappingJackson2HttpMessageConverter) converter).forEach(converter -> {
converter.setObjectMapper(customObjectMapper());
converter.setPrettyPrint(true);
List<MediaType> mediaTypes = new ArrayList<>(converter.getSupportedMediaTypes());
mediaTypes.add(MediaType.APPLICATION_JSON);
converter.setSupportedMediaTypes(mediaTypes);
});
})
.build()
);
return HttpServiceProxyFactory
.builder()
.exchangeAdapter(httpExchangeAdapter)
.build();
}
public ObjectMapper customObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
// 其他配置...
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// 匹配不上的字段忽略,宽松模式
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 允许出现特殊字符和转义符
objectMapper.configure(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
// 允许出现单引号
objectMapper.configure(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
javaTimeModule.addSerializer(Date.class, new DateSerializer(false, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
javaTimeModule.addDeserializer(Date.class, new com.fasterxml.jackson.databind.JsonDeserializer<Date>() {
@Override
public Date deserialize(com.fasterxml.jackson.core.JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
try {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(p.getText());
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
});
objectMapper.registerModule(javaTimeModule);
return objectMapper;
}
}
标签:HttpExchange,converter,Spring,dd,yyyy,javaTimeModule,new,序列化,objectMapper
From: https://www.cnblogs.com/jiayuan2006/p/18198117