Spring3.2 Jackson RestApi Json null⇒空白変換

Spring3.2&Jacksonを使用してRestAPI(Jsonデータを返却)を開発する時にnull⇒空白変換にはまった。。。
前も同じような事ではまった気がするので今回はメモを残す。(前回、、、)

色々割愛して書くと以下の2パターンに行きつく。

①Beanに@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)と書いとけば幸せになれる。
②servlet-context.xmlに以下のような事を書くと幸せになれる。(NullValueSerializerの実装は別途必要)

	<bean id="nullValueSerializer" class="{NullValueSerializerを実装したクラス}" />
	<bean id="serializerProvider" class="org.codehaus.jackson.map.ser.StdSerializerProvider" >
		<property name="nullValueSerializer" ref="nullValueSerializer" />
	</bean>
	<bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper">
		<property name="serializerProvider" ref="serializerProvider" />
	</bean>
	<bean id="annotationMethodHandlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
					<property name="objectMapper" ref="jacksonObjectMapper" />
				</bean>
				<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
				<bean class="org.springframework.http.converter.StringHttpMessageConverter">
					<property name="writeAcceptCharset" value="false" />
				</bean>
				<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter" />
				<bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter" />
			</list>
		</property>
	</bean>

①はnullの値を保持する項目は出力しない。
②はnullの値をNullValueSerializerで実装した内容にて置き換える。

今回やりたい事としては①パターン(項目毎出力されない)ではしっくりこない為、
②のパターンを採用。(はまった)

実際に②の記載をのっけてTomcatを起動してAPIをキックするとnull⇒null
(正しくは(null ⇒ “幸せ”) ⇒ null(現実))

【調査】

・設定が間違っていると思い見直してみる。⇒特に問題なし。
・あきらめてデバッグする。
⇒NullValueSerializerインスタンスは生成され、設定した内容で反映もされている。
ただし、API返却時に使用されているObjectMapperからの流れではNullValueSerializerは使用されない。。。
・いったんあきらめる。
・それもあきらめて関係するライブラリ側の実装を見る。
⇒AnnotationMethodHandlerAdapterの実装を見ると@Deprecated(Spring3.2から。。。)になっており
RequestMappingHandlerAdapterと書いてある。
・以下の修正。

<bean id="annotationMethodHandlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  ↓↓↓
<bean id="requestMappingHandlerAdapter" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">

・結果として幸せが帰る。

【まとめ】

Spring3.1はAnnotationMethodHandlerAdapter
Spring3.2はRequestMappingHandlerAdapter
を使用する。(パッケージも微妙に変わっているので注意。。)
(あきらめない)


ホームページ http://www.ois-yokohama.co.jp

facebook   https://www.facebook.com/orientalinformationservice/

 

\ 最新情報をチェック /