java - Spring Boot MVC/Rest Controller 和枚举反序列化转换器

标签 java spring spring-mvc spring-boot spring-restcontroller

在我的 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用于转换InputStreamString 。但您可以以任何首选方式进行。

现在您已在 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/

相关文章:

JAVA - 如何使用原始 PDF 和单独的 PKCS#7 签名数据创建签名 PDF

java - 使实例同时只能由一个线程访问吗?

java - 使用增强的 For 循环语法输出较慢的结果

spring - 当Specification和Pageable一起使用时如何禁用计数?

java - Spring Security 忽略失败的身份验证

java - 如何获取 Spring MVC 中路径剩余部分的路径变量?

Java - Servlet,在整个项目中携带登录信息( session bean)

spring - spring数据elasticsearch继承没有查询结果

java - 如何在Spring Boot中从目标文件夹读取java文件

java - 查看 SPRING BOOT 中的解析器设置问题