在我的 Spring Boot 应用程序中,我有一个以下 @RestController
方法:
@RequestMapping(value = "/{decisionId}/decisions", method = RequestMethod.POST)
public List<DecisionResponse> getChildDecisions(@PathVariable Long decisionId, @Valid @RequestBody Direction direction) {
}
我使用枚举org.springframework.data.domain.Sort.Direction
作为请求正文。
现在,Spring 内部逻辑无法在收到客户端请求后反序列化此 Direction
枚举。
您能否展示如何编写自定义枚举转换器(或类似的东西)并使用 Spring Boot 配置它,以便能够从客户端请求反序列化 Direction
枚举?还应该允许 null
值。
最佳答案
首先,您应该创建自定义转换器类,该类实现 HttpMessageConverter<T>
接口(interface):
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);
}
}
关于java - Spring Boot MVC/Rest Controller 和枚举反序列化转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41539120/