2013年10月25日金曜日

Spring 3.xでJSON型を返す@Controllerのクラスを実装する時に気をつけたい事

Spring 3.xで@Controllerのクラスを実装して、JSON型を返すRESTfulなサービスを作る時に気をつけたい事がある。ここは少しハマった。。。

まず仕様の抜粋から、

Underneath the covers, Spring MVC delegates to a HttpMessageConverter to perform the serialization. In this case, Spring MVC invokes a MappingJacksonHttpMessageConverter built on the Jackson JSON processor. This implementation is enabled automatically when you use the mvc:annotation-driven configuration element with Jackson present in your classpath.

つまり、Spring MVCはJSONの場合、JavaオブジェクトのシリアライズをMappingJacksonHttpMessageConverterに委譲する。その為には、applicationContext.xmlで<mvc:annotation-driven/>を追加しないと委譲が行われない。そして、これはメソッドの戻り値が@ResponseBodyで指定される。

そして、ハマったところ。。。

JSONにマップするクラスがgetter/setterを持っていない場合、HTTP 406のエラーコードが返されてうまくいかない。つまりJavaBeansでなければならないよう。おそらくMessageConverterの仕様でしょうが、ここがブラックボックスで分からない。。(?)

ということで、ここには気をつけましょう。


  1. <mvc:annotation-driven/>
  2. jackson-mapper-asl.jar, jackson-xc.jarが必要
  3. @ResponseBody
  4. JavaBeans(?)パターンの実装 -------> 調査中


http://spring.io/blog/2010/01/25/ajax-simplifications-in-spring-3-0/

0 件のコメント:

コメントを投稿