2017-01-08 8 views
0

私は、次の@RestControllerの方法があります。春ブーツMVC /休憩コントローラと列挙型のデシリアライゼーションコンバータ

@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 enum

クライアントリクエストからDirection列挙型をデシリアライズできるように、カスタムの列挙型コンバータ(またはそのようなもの)を作成してSpringブートで設定する方法を教えてください。また、nullの値を許可する必要があります。

+0

をあなたは、要求メッセージの例を投稿してくださいもらえますか? – 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 { 

    } 

} 

私はStringへの改宗InputStreamためApache Commons IOからIOUtilsを使用。しかし、あなたはそれを好みの方法で行うことができます。

これで、Springコンバーターリストに登録されたコンバーターを登録しました。

<mvc:annotation-driven> 
    <mvc:message-converters> 
     <bean class="com.somepackage.DirectionConverter"/> 
    </mvc:message-converters> 
</mvc:annotation-driven> 

それとも、Javaの設定使用している場合:次の<mvc:annotation-driven>タグに追加

@EnableWebMvc 
@Configuration 
public class WebConfig extends WebMvcConfigurerAdapter { 

    @Override 
    public void configureMessageConverters(
     List<HttpMessageConverter<?>> converters) {  
     messageConverters.add(new DirectionConverter()); 
     super.configureMessageConverters(converters); 
    } 
} 
関連する問題