Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java SpringREST服务:如何配置以删除json响应中的空对象_Java_Spring_Jackson - Fatal编程技术网

Java SpringREST服务:如何配置以删除json响应中的空对象

Java SpringREST服务:如何配置以删除json响应中的空对象,java,spring,jackson,Java,Spring,Jackson,我有一个SpringWebService,它返回json响应。我使用这里给出的示例创建服务: json返回的格式为: {“name”:null,“staffName”:[“kfc kampar”,“smith”]} 我想从返回的响应中删除任何空对象,因此如下所示: {“员工姓名”:[“肯德基坎帕”,“史密斯”]} 我发现这里也有类似的问题,但我能找到一个可行的解决方案 通过阅读这些和其他来源,我认为实现我想要的最干净的方法是使用Spring3.1和可以在mvc注释中配置的消息转换器

我有一个SpringWebService,它返回json响应。我使用这里给出的示例创建服务:

json返回的格式为: {“name”:null,“staffName”:[“kfc kampar”,“smith”]}

我想从返回的响应中删除任何空对象,因此如下所示: {“员工姓名”:[“肯德基坎帕”,“史密斯”]}

我发现这里也有类似的问题,但我能找到一个可行的解决方案

通过阅读这些和其他来源,我认为实现我想要的最干净的方法是使用Spring3.1和可以在mvc注释中配置的消息转换器。 我更新的spring配置文件是:

<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>
我使用的Jackson罐子是Jackson mapper asl 1.9.0和Jackson core asl 1.9.0。这些是我从mkyong.com下载的SpringJSON项目中唯一添加到pom的新JAR

项目成功构建,但当我通过浏览器调用服务时,我仍然得到相同的结果,即。 {“name”:null,“staffName”:[“kfc kampar”,“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;
}
现在,如果我调用服务,我会得到预期的结果,即。 {“员工姓名”:[“肯德基坎帕”,“克罗宁”]}

我还能够使用@JsonIgnore注释使其工作,但是这个解决方案不适合我


我不明白为什么它是在代码中工作,而不是在配置中工作,所以任何帮助都会非常好。

我通过配置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>

非空
这当然与其他问题中给出的回答类似,例如

需要注意的重要一点是,mvc:annotation-driven和AnnotationMethodHandlerAdapter不能在同一上下文中使用

但我仍然无法让它与Spring3.1和mvc一起工作:注释驱动。我认为,一个使用mvc的解决方案:注释驱动和所有伴随它而来的好处会更好。如果有人能告诉我怎么做,那就太好了。

你可以用老版本的杰克逊


对于Jackson 1.9+,请使用。

如果您使用的是Jackson 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>

自Jackson 2.0以来,您可以使用


从版本1.6开始,我们有了新的注释JsonSerialize(例如在版本1.9.9中)

例如:

@JsonSerialize(include=Inclusion.NON_NULL)
public class Test{
...
}
@JsonWriteNullProperties(false)
public class Test{
    ...
}
默认值始终为

在旧版本中,您可以使用JsonWriteNullProperties,这在新版本中已被弃用。 例如:

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

从Jackson 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 2.0或更高版本,请使用
@JsonInclude(Include.NON\u NULL)


这将删除空对象和空对象。

由于正在使用Jackson,您必须将其配置为Jackson属性。对于Spring引导REST服务,您必须在
application.properties
application.yml
中配置它:

spring.jackson.default-property-inclusion = NON_NULL

设置
spring.jackson.default property inclusion=non_null
选项是最简单的解决方案,效果很好

但是如果在代码中的某个地方实现WebMVCConfiguer,请小心,否则属性解决方案将无法工作,您必须在代码中设置非空序列化,如下所示:

@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);
    }
}
@配置
@EnableWebMvc
公共类WebConfig实现WebMVCConfiguer{
//你的一些配置在这里。。。
@凌驾

public void configureMessageConverters(列表对于我来说,spring似乎没有使用contex文件中定义的映射器对象,我通过调试检查spring正在调用
setSerializationInclusion()
xmlYa中定义的映射器对象的方法我也是这样理解的。对象映射器似乎配置正确,只是没有在spring容器中使用。不幸的是,一位主持人删除了我的回答,声称这些是重复的问题。但他是Python的人,可能看不到这些是不同的Java Spring问题(一个用于Spring MVC,另一个用于Spring REST)。他删除了最重要问题中的一个。顺便说一句,没有办法跟踪。答案是一样的。库是一样的(Jackson)。我会再试一次,以帮助社区。属性名称已更改为
spring.jackson。默认属性include=NON_NULL
。工作正常!很酷,我正在寻找的这个。无需更改所有POJO并将其放在一个地方。感谢您节省我的时间!
@JsonSerialize(include=include.NON_NULL)
已弃用
@deprecated//自2.0以来,在2.6中标记为已弃用
感谢您提及实施WebMVCConfiguer时对属性的影响。它解决了我的问题。这就是我想要的。谢谢
spring.jackson.default-property-inclusion = 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);
    }
}