2012-10-03 23 views
35

私はjsonレスポンスを返すspring webserviceを持っています。私は、サービスを作成するためにここに挙げた例を使用しています: http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/Spring REST Service:jsonレスポンスでヌルオブジェクトを削除する方法

JSONがで返される形式は次のとおりです。 {「名前」:ヌル、「staffName」:[「KFC-kampar」、「スミス」私は、同様のことがわかりました[ "KFC-kampar"、 "スミス"]}

: { "staffName":それは次のようになりますので、私は返された応答から任意のヌルオブジェクトを削除する]}

ここで質問された質問ですが、私は解決策を得ることができました。

Configuring ObjectMapper in Spring

How to configure MappingJacksonHttpMessageConverter while using spring annotation-based configuration?

configuring the jacksonObjectMapper not working in spring mvc 3

how to configure spring mvc 3 to not return "null" object in json response?

Spring configure @ResponseBody JSON format

Jackson+Spring3.0.5 custom object mapper

これらの情報源やその他の情報源を読んで、私が望むことを達成する最もクリーンな方法は、Spring 3.1とmvc-annotation内で構成できるメッセージコンバータを使用することでした。 私の更新のバネの設定ファイルは次のとおりです。

<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:context="http://www.springframework.org/schema/context" 
xmlns:mvc="http://www.springframework.org/schema/mvc" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation=" 
    http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.1.xsd 
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"> 

<context:component-scan base-package="com.mkyong.common.controller" /> 

<mvc:annotation-driven> 
    <mvc:message-converters> 
     <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> 
      <property name="prefixJson" value="true" /> 
      <property name="supportedMediaTypes" value="application/json" /> 
      <property name="objectMapper"> 
       <bean class="org.codehaus.jackson.map.ObjectMapper"> 
        <property name="serializationInclusion" value="NON_NULL"/> 
       </bean> 
      </property> 
     </bean> 
    </mvc:message-converters> 
</mvc:annotation-driven> 

mkyong.comサイト上で与えられたとして、それは

すなわちヌルですので、私はショップ名変数の設定をコメントアウト以外のサービスクラスは、同じです
@Controller 
@RequestMapping("/kfc/brands") 
public class JSONController { 
    @RequestMapping(value="{name}", method = RequestMethod.GET) 
    @ResponseStatus(HttpStatus.OK) 
    public @ResponseBody Shop getShopInJSON(@PathVariable String name) { 
     Shop shop = new Shop(); 
     //shop.setName(name); 
     shop.setStaffName(new String[]{name, "cronin"}); 
     return shop; 
    } 
} 

私が使っているジャーナルジャーは、jackson-mapper-asl 1.9.0とjackson-core-asl 1.9.0です。これらは、私がmkyong.comからダウンロードしたspring-jsonプロジェクトの一部として提供されているように、私がpomに追加した唯一の新しい瓶です。

プロジェクトが正常にビルドが、私はブラウザを介してサービスを起動したときに、私はまだ同じことすなわち 取得{「名前」:ヌル、「staffName」:[「KFC-kampar」、「スミス」]}

私の設定でどこが間違っているか教えていただけますか?

私はいくつかのオプションを試しましたが、JSONControllerにObject Mapperを追加し、 "getShopInJSON"メソッドで文字列、つまり

を返すことが、jsonを正しい形式で返すことができた唯一の方法です。

私も仕事にそれを得ることができました:私は、私が期待すなわち {[「KFC-kampar」、「クローニン」]「staffNameを」}取得サービスを呼び出す場合は今

public @ResponseBody String getShopInJSON(@PathVariable String name) throws JsonGenerationException, JsonMappingException, IOException { 
    ObjectMapper mapper = new ObjectMapper(); 
    mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); 

    Shop shop = new Shop(); 
    //shop.setName(name); 
    shop.setStaffName(new String[]{name, "cronin"}); 
    String test = mapper.writeValueAsString(shop); 
    return test; 
} 

@JsonIgnoreアノテーションを使用していますが、この解決法は私には適していません。

なぜコードで動作しているのですが、設定には反映されていないため、何か助けになるのは分かりません。

+1

春iは、デバッグスプリングで確認、コンテックスファイルで定義されたマッパーオブジェクトを使用していないように見えましたxml – Elbek

+1

で定義されているマッパーオブジェクトの 'setSerializationInclusion()'メソッドを呼び出すのです。オブジェクトマッパーは正しく設定されているように見えますが、スプリングコンテナでは使用されていません。 – mikec

答えて

1

私はSpringコンテナを設定することで解決策を見つけましたが、それでも私が望むものではありません。

私は削除、バック春3.0.5にロールバックし、その中に私は私の設定ファイルを変更する場所です:これは、もちろん、例えば他の質問に与えられた回答に似て

<bean 
    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> 
     </list> 
    </property> 
</bean> 


<bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" /> 
<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig" 
    factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" /> 
<bean 
    class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> 
    <property name="targetObject" ref="jacksonSerializationConfig" /> 
    <property name="targetMethod" value="setSerializationInclusion" /> 
    <property name="arguments"> 
     <list> 
      <value type="org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion">NON_NULL</value> 
     </list> 
    </property> 
</bean> 

configuring the jacksonObjectMapper not working in spring mvc 3

注意すべき重要なことは、MVCということです:注釈駆動型とAnnotationMethodHandlerAdapterが同じコンテキストで使用することはできません。

私はまだSpring 3.1とmvc:annotation-drivenで動作させることができません。 mvc:annotation-drivenを使用するソリューションとそれに伴うすべての利点は、私が考えるよりはるかに優れています。誰かが私にこれを行う方法を示すことができれば、それは素晴らしいだろう。

5

あなたは、メッセージ・コンバータタグをジャクソン2を使用している場合である。

<mvc:annotation-driven> 
    <mvc:message-converters> 
     <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> 
      <property name="prefixJson" value="true"/> 
      <property name="supportedMediaTypes" value="application/json"/> 
      <property name="objectMapper"> 
       <bean class="com.fasterxml.jackson.databind.ObjectMapper"> 
        <property name="serializationInclusion" value="NON_NULL"/> 
       </bean> 
      </property> 
     </bean> 
    </mvc:message-converters> 
</mvc:annotation-driven> 
50

ジャクソン2.0ので、バージョン1.6以来、私たちはバージョンで新しい注釈JsonSerializeを(持っているあなたはJsonInclude

@JsonInclude(Include.NON_NULL) 
public class Shop { 
    //... 
} 
2

を使用することができます例えば1.9.9)。

例:

@JsonSerialize(include=Inclusion.NON_NULL) 
public class Test{ 
... 
} 

デフォルト値は常にあります。

古いバージョンでは、JsonWriteNullPropertiesを使用できます.JsonWriteNullPropertiesは、新しいバージョンでは非推奨です。 例:

ジャクソン2.0、 @JsonSerialize(include = xxx)のよう
@JsonWriteNullProperties(false) 
public class Test{ 
    ... 
} 
+0

'' @JsonSerialize(include = Inclusion.NON_NULL) ''は非難して – cheloncio

5

は、すべてあなたの非XML設定の人々のために@JsonInclude

3

の賛成で廃止されました:

ObjectMapper objMapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL); 
HttpMessageConverter msgConverter = new MappingJackson2HttpMessageConverter(objMapper); 
restTemplate.setMessageConverters(Collections.singletonList(msgConverter)); 
2
@JsonSerialize(include=JsonSerialize.Inclusion.NON_EMPTY) 
public class Shop { 
    //... 
} 

この意志空と空の両方を削除するオブジェクト

19

ジャクソンが使用されているので、ジャクソンのプロパティとして設定する必要があります。春ブーツRESTサービスの場合は、あなたはapplication.propertiesでそれを設定する必要があります。私にとって

spring.jackson.default-property-inclusion=NON_NULL 

source

+2

を非難しました。しかし、彼はPythonの人で、Java Springのさまざまな質問(Spring MVCのためのもの、Spring RESTのためのもの)が異なることが分かりました。彼は最も重要な質問の1つを削除した。ところで、テーラリングする方法はありません。答えは同じです。図書館は同じです(ジャクソン)。私はコミュニティを助けるために、もう一度お試しになります。 –

+12

プロパティ名が 'spring.jackson.default-property-inclusion = NON_NULL'に変更されました。正常に動作します! – Miguel

関連する問題