背景
与 Spring:自定义 Converter 实现参数转换 ,需求类似,但经过测试及源码分析,上述实现只针对GET接口有效。针对POST接口,可以按以下方式将参数从yyyy-MM-dd HH:mm:ss
转化为yyyy-MM-dd
。
实现
自定义反序列化器(实现ObjectDeserializer接口,自定义匹配、转换逻辑)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class BizDateDeserializer implements ObjectDeserializer {
public <T> T deserialze(DefaultJSONParser parser, Type type, Object o) {
if (type.getTypeName().equals(Date.class.getName())) {
Date date = parser.parseObject(Date.class);
return (T) DateUtil.beginOfDay(date);
} else if (String.class.getName().equals(type.getTypeName())) {
String date = parser.parseObject(String.class);
return (T) DateUtil.beginOfDay(DateUtil.parse(date));
}
return (T) parser.parseObject(type.getClass());
}
public int getFastMatchToken() {
return ObjectDeserializer.super.getFastMatchToken();
}
}添加自定义的反序列化器到fastJson转换器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class IWebMvcConfigurer implements WebMvcConfigurer {
private BizDateDeserializer bizDateDeserializer;
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
if (CollUtil.isNotEmpty(converters)) {
for (HttpMessageConverter<?> converter : converters) {
if (converter instanceof FastJsonHttpMessageConverter) {
FastJsonConfig fastJsonConfig =
((FastJsonHttpMessageConverter) converter).getFastJsonConfig();
fastJsonConfig
.getParserConfig()
.putDeserializer(BizDateDeserializer.class, bizDateDeserializer);
}
}
}
}
}使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class RoomSearchQuery {
private Date beginDate;
private Date endDate;
private List<String> stas;
private List<String> roomTypes;
//......
}