首先你应该创建自定义转换器类,实现HttpMessageConverter<T> 接口:
package com.somepackage;
public class DirectionConverter implements HttpMessageConverter<Sort.Direction> {
public boolean canRead(Class<?> aClass, MediaType mediaType) {
return aClass== Sort.Direction.class;
}
public boolean canWrite(Class<?> aClass, MediaType mediaType) {
return false;
}
public List<MediaType> getSupportedMediaTypes() {
return new LinkedList<MediaType>();
}
public Sort.Direction read(Class<? extends Sort.Direction> aClass,
HttpInputMessage httpInputMessage)
throws IOException, HttpMessageNotReadableException {
String string = IOUtils.toString(httpInputMessage.getBody(), "UTF-8");
//here do any convertions and return result
}
public void write(Sort.Direction value, MediaType mediaType,
HttpOutputMessage httpOutputMessage)
throws IOException, HttpMessageNotWritableException {
}
}
我使用IOUtils 从Apache Commons IO 将InputStream 转换为String。但是你可以用任何喜欢的方式来做。
现在您已经在 Spring 转换器列表中注册了创建的转换器。添加到<mvc:annotation-driven>标签下:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="com.somepackage.DirectionConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
或者如果您使用的是 java 配置:
@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(
List<HttpMessageConverter<?>> converters) {
messageConverters.add(new DirectionConverter());
super.configureMessageConverters(converters);
}
}