【问题标题】:Spring Boot MVC/Rest controller and enum deserialization converterSpring Boot MVC/Rest 控制器和枚举反序列化转换器
【发布时间】:2017-05-23 04:32:00
【问题描述】:

在我的 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 值。

【问题讨论】:

  • 你能发一个请求消息的例子吗?

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


【解决方案1】:

首先你应该创建自定义转换器类,实现HttpMessageConverter&lt;T&gt; 接口:

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 {

    }

}

我使用IOUtilsApache Commons IOInputStream 转换为String。但是你可以用任何喜欢的方式来做。

现在您已经在 Spring 转换器列表中注册了创建的转换器。添加到&lt;mvc:annotation-driven&gt;标签下:

 <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);
    }
}

【讨论】:

    猜你喜欢
    • 2018-10-18
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    相关资源
    最近更新 更多