programing

Spring REST 서비스: json 응답의 null 개체를 제거하도록 구성하는 방법

codeshow 2023. 3. 18. 09:12
반응형

Spring REST 서비스: json 응답의 null 개체를 제거하도록 구성하는 방법

json 응답을 반환하는 스프링 웹 서비스가 있습니다.여기 제시된 예를 사용하여 서비스를 만듭니다.http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/

json이 반환되는 형식은 {"name":null,staffName"입니다.["smith"]

다음과 같이 반환된 응답에서 null 개체를 모두 제거하고 싶습니다. {"staffName":["smith"]

여기서도 비슷한 질문을 할 수 있었습니다만, 해결 방법을 찾을 수 있었습니다.

스프링에서의 오브젝트매퍼 설정

스프링 주석 기반 구성을 사용하는 동안 MappingJacksonHttpMessageConverter를 설정하려면 어떻게 해야 합니까?

spring mvc 3에서 동작하지 않음jacksonObjectMapper 설정

json 응답에서 "spring mvc 3" 개체를 반환하지 않도록 설정하는 방법

스프링 구성 @ResponseBody JSON 형식

Jackson+Spring 3.0.5 커스텀 오브젝트 맵퍼

이러한 정보 및 기타 소스를 통해 제가 원하는 것을 달성하는 가장 깔끔한 방법은 Spring 3.1과 mvc 주석 내에서 설정할 수 있는 메시지 컨버터를 사용하는 것이라고 생각했습니다.업데이트된 스프링 구성 파일은 다음과 같습니다.

<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 사이트에서 지정한 것과 동일합니다.단, Shop name 변수 설정을 코멘트하여 무효로 했습니다.

@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;
    }
}

제가 사용하고 있는 잭슨 항아리는 잭슨-매퍼-asl 1.9.0과 잭슨-코어-asl 1.9.0입니다.mkyong.com에서 다운받은 spring-json 프로젝트의 일환으로 pom에 추가한 유일한 새로운 항아리입니다.

프로젝트는 정상적으로 구축되지만 브라우저를 통해 서비스를 실행해도 동일한 메시지가 나타납니다. 예를 들어 {"name":null, staffName:["smith"]

내 구성에 어떤 문제가 있는지 누가 말해 줄 수 있나요?

다른 몇 가지 옵션을 시도했지만 올바른 형식으로 json을 반환할 수 있는 유일한 방법은 객체 매퍼를 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"}이(가) 표시됩니다.["contain"", "contain"]}

또, @JsonIgnore 주석을 사용해 동작시킬 수 있었습니다만, 이 솔루션은 저에게 적합하지 않습니다.

왜 코드에서는 동작하지만 설정에서는 동작하지 않는지 이해할 수 없기 때문에 어떤 도움말도 도움이 됩니다.

Jackson 2.0이므로 JsonInclude를 사용할 수 있습니다.

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

잭슨을 사용하고 있기 때문에 잭슨 속성으로 설정해야 합니다. Spring Boot REST에서 .application.properties ★★★★★★★★★★★★★★★★★」application.yml:

spring.jackson.default-property-inclusion = NON_NULL

원천

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

2.0 의 경우 Jackson 2.0 사용@JsonInclude(Include.NON_NULL)

그러면 빈 개체와 null 개체가 모두 제거됩니다.

의 설정spring.jackson.default-property-inclusion=non_null옵션은 가장 간단한 해결책으로 잘 작동합니다.

다만, WebMvcConfigurer 를 코드로 실장하는 경우는, 속성 솔루션이 동작하지 않기 때문에, 코드로 NON_NULL 의 시리얼화를 다음과 같이 설정할 필요가 있습니다.

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    // some of your config here...

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter(objectMapper);
        converters.add(jsonConverter);
    }
}

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

버전 1.6 이후 새로운 주석 JsonSerialize(예: 버전 1.9.9)가 추가되었습니다.

예:

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

기본값은 ALways 입니다.

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

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

2.0 of슨2 . 0 。@JsonSerialize(include = xxx) 위해 폐지되었습니다.@JsonInclude

xml 이외의 모든 구성 사용자:

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

잭슨의 이전 버전에 사용할 수 있습니다.

Jackson 1.9+의 경우 를 사용합니다.

Spring 컨테이너 구성을 통해 해결 방법을 찾아냈지만, 여전히 제가 원하던 방법이 아닙니다.

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>

이는 물론 다른 질문의 답변과 유사합니다.

spring mvc 3에서 동작하지 않음jacksonObjectMapper 설정

주의할 점은 mvc:notation-drived와 AnnotationMethodHandlerAdapter는 동일한 컨텍스트에서 사용할 수 없다는 것입니다.

Spring 3.1 및 mvc:notation-drived에서는 아직 사용할 수 없습니다.mvc: 주석 기반 솔루션과 그에 따른 모든 이점을 사용하는 솔루션이 훨씬 더 낫다고 생각합니다.누가 이걸 어떻게 하는지 알려준다면 좋을 것 같아요.

언급URL : https://stackoverflow.com/questions/12707165/spring-rest-service-how-to-configure-to-remove-null-objects-in-json-response

반응형