2012-10-03 3 views
35

json 응답을 리턴하는 스프링 webservice가 있습니다. json으로이 반환됩니다 http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/Spring REST Service : json 응답에서 null 객체를 제거하도록 구성하는 방법

형식은 다음과 같습니다 : 나는 서비스를 만들려면 여기 주어진 예제를 사용하고 { "이름": 널 (null) "staffName": [ "KFC-캄파 르", "스미스" ]}

은 다음과 같습니다 그래서 반환 된 응답에서에 null 개체를 제거 할

: { "staffName": [ "KFC는-캄파 르", "스미스는"]}

나는 유사한 발견했습니다 질문은 여기에 있지만 나는 일하는 해결책을 얻을 수 있었다.

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 내에서 구성 할 수있는 메시지 변환기를 사용하는 것이 가장 깨끗한 방법이라고 생각했습니다. 내 업데이트 스프링 설정 파일은 다음과 같습니다 mkyong.com 사이트에 주어진대로

즉, 널 (null) 그래서 나는 가게 이름 변수의 설정에서 주석을 제외하고

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

서비스 클래스, 동일

@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에 추가 된 유일한 새로운 항아리입니다.

이 프로젝트는 성공적으로 빌드,하지만 난 브라우저를 통해 서비스를 호출 할 때 난 여전히 같은 일을 얻을 즉 { "이름": 널 (null) "staffName": [ "스미스" "KFC-캄파 르"]}

누구나 내 구성이 잘못 될 수 있습니다.

다른 여러 옵션을 시도했지만 정확한 형식으로 json을 반환 할 수있는 유일한 방법은 Object Mapper를 JSONController에 추가하고 "getShopInJSON"메서드에서 문자열 (예 :

)을 반환하는 것입니다. 나는이 즉 예상 얻을 서비스를 호출 할 경우
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; 
} 

이제 { "staffName을": [ "KFC-캄파 르", "크로닌"]} 나는 또한 얻을 수있었습니다

그것은 작동합니다 @JsonIgnore 주석을 사용하지만이 솔루션은 저에게 적합하지 않습니다.

코드에서 작동하지만 구성에서 작동하지 않는 이유를 이해할 수 없으므로 도움이 될 것입니다.

+1

, 난 디버그 스프링 확인 xml – Elbek

+1

에 정의 된 매퍼 객체에 대해'setSerializationInclusion()'메소드를 호출하고 있습니다. 객체 매퍼는 올바르게 구성되어있는 것으로 보이며 스프링 컨테이너에서 사용되지 않고 있습니다. – mikec

답변

1

스프링 컨테이너 구성을 통해 해결책을 찾았지만 여전히 원하는 것은 아닙니다.

나는 제거 봄 3.0.5로 롤백하고 장소 년대에 나는 내 config 파일을 변경 :

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

이것은 예를 들어, 다른 질문에 주어진 반응의 과정과 유사하다 주석 기반 및 AnnotationMethodHandlerAdapter 같은 맥락에서 사용할 수 없습니다

configuring the jacksonObjectMapper not working in spring mvc 3

중요한 점은 MVC는 점이다.

나는 스프링 3.1과 mvc : annotation-driven으로 작업 할 수 없다. mvc : annotation-driven를 사용하는 솔루션과이 솔루션에 수반되는 모든 이점이 훨씬 더 좋을 것이라고 생각합니다. 누구든지 나에게이 일을하는 법을 보여줄 수 있다면 그것은 좋을 것이다.

5

는 잭슨이 사용하는 경우, 메시지 컨버터 태그는 다음과 같습니다

<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 이후 버전에서 (우리는 새로운 주석 JsonSerialize이 버전 1.6 이후 JsonInclude

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

을 사용할 수 있습니다 예를 들면 1.9.9).

예 :

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

기본값 ALWAYS이다.

이전 버전에서는 새 버전에서 더 이상 사용되지 않는 JsonWriteNullProperties를 사용할 수 있습니다. 예 :

ObjectMapper objMapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL); 
HttpMessageConverter msgConverter = new MappingJackson2HttpMessageConverter(objMapper); 
restTemplate.setMessageConverters(Collections.singletonList(msgConverter)); 
+0

''@JsonSerialize (include = Inclusion.NON_NULL)''불행히도 – cheloncio

5

@JsonSerialize(include = xxx)는 비 XML 구성 사람 모두 들어 @JsonInclude

3

에 찬성 중지되었습니다 빈 객체와 null 객체를 모두 제거하십시오. 객체

2
@JsonSerialize(include=JsonSerialize.Inclusion.NON_EMPTY) 
public class Shop { 
    //... 
} 

을이 의지 잭슨 2.0로

@JsonWriteNullProperties(false) 
public class Test{ 
    ... 
} 
19

Jackson이 사용 중이므로이를 Jackson 속성으로 구성해야합니다.봄 부팅 REST 서비스의 경우에, 당신은 application.properties에 구성해야합니다 : 그것은 텍스 파일에 정의 된 매퍼 개체를 사용하지 않는 스프링 듯 나를 위해

spring.jackson.default-property-inclusion=NON_NULL 

source

+2

을 사용하지 않아서 중재자가 질문을 반복하여 내 답변을 삭제했습니다. 하지만 그는 Python 사용자이고 Java Spring의 다른 질문 (Spring MVC 용, Spring REST 용)이 다를 수도 있습니다. 그는 가장 중요한 질문에서 그 사람을 삭제했습니다. BTW, 방법은 없습니다. 대답은 같습니다. 도서관은 동일합니다 (Jackson). 커뮤니티를 돕기 위해 다시 시도하겠습니다. –

+12

속성 이름이'spring.jackson.default-property-inclusion = NON_NULL'으로 변경되었습니다. 잘 작동합니다! – Miguel

관련 문제