2017-01-08 19 views
0

在我的春節,啓動應用程序我有以下@RestController方法:春引導MVC/REST控制器和反序列化的枚舉器

@RequestMapping(value = "/{decisionId}/decisions", method = RequestMethod.POST) 
    public List<DecisionResponse> getChildDecisions(@PathVariable Long decisionId, @Valid @RequestBody Direction direction) { 
    } 

我用枚舉org.springframework.data.domain.Sort.Direction作爲請求主體。

現在春天的內部邏輯無法反序列化這個Direction枚舉後,客戶端的請求。

請問您能展示如何編寫一個自定義enum轉換器(或類似的東西)並使用Spring Boot進行配置,以便能夠從客戶端請求反序列化Direction enum?還應該允許值爲null

+0

能否請您POST請求消息的例子嗎? – chaoluo

回答

1

首先應創建自定義轉換器類,實現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 { 

    } 

} 

我以前IOUtilsApache 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); 
    } 
}