Spring REST服务:如何配置在json响应中删除空对象 [英] Spring REST Service: how to configure to remove null objects in json response

查看:100
本文介绍了Spring REST服务:如何配置在json响应中删除空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个spring webservice,它返回一个json响应。我正在使用此处给出的示例来创建服务:
http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/

I have a spring webservice that returns a json response. I'm using the example given here to create the service: http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/

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

The format the json is returned in is: {"name":null,"staffName":["kfc-kampar","smith"]}

我想从返回的响应中删除任何空对象,使其如下所示:
{staffName:[kfc-kampar,smith]}

I want to remove any null objects from the returned response so it looks like this: {"staffName":["kfc-kampar","smith"]}

我在这里发现了类似的问题,但我已经能够找到解决方案,例如

I've found similar questions asked here but I've been able to get a solution working e.g.

在Spring中配置ObjectMapper

如何在使用基于spring注释的配置时配置MappingJacksonHttpMessageConverter?

配置jacksonObjectMapper在春季不工作mvc 3

如何配置spring mvc 3不返回" null" json响应中的对象?

Spring配置@ResponseBody JSON格式

Jackson + Spring3.0.5自定义对象映射器

通过阅读这些和其他来源,我想到了实现目标的最简洁方法我想要使​​用Spring 3.1和可以在mvc-annotation中配置的消息转换器。
我更新的spring配置文件是:

From reading through these and other sources, I figured the cleanest way to achieve what I wanted was to use Spring 3.1 and the message-converters that can be configured within the mvc-annotation. My updated spring config file is:

<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网站上给出,除了我注释了商店名称变量的设置所以它是空的,即

The service class is the same as given on the mkyong.com site, except I commented out the setting of the Shop name variable so it's null i.e.

@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罐子是jackson-mapper -asl 1.9.0和jackson-core-asl 1.9.0。这是我添加到pom中的唯一新罐子,作为我从mkyong.com下载的spring-json项目的一部分提供。

The Jackson jars I'm using are jackson-mapper-asl 1.9.0 and jackson-core-asl 1.9.0. These are the only new jars I've added to the pom as provided as part of the spring-json project I downloaded from mkyong.com.

项目构建成功,但是当我通过浏览器调用服务时,我仍然得到同样的东西,即
{name:null,staffName:[kfc-kampar,smith]}

The project builds successfully, but when I invoke the service through the browser I still get the same thing i.e. {"name":null,"staffName":["kfc-kampar","smith"]}

谁能告诉我我的配置出错了?

Can anyone tell me where I'm going wrong with my configuration?

我已经尝试了其他几个选项,但是我能够以正确的格式返回json的唯一方法是将Object mapper添加到JSONController中让getShopInJSON方法返回一个字符串,即

I've tried several other options, but the only way I've been able to return the json in the correct format is to add the Object mapper to the JSONController and have the "getShopInJSON" method return a string i.e.

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-kampar,cronin]}

Now if I invoke the service I get the expected i.e. {"staffName":["kfc-kampar","cronin"]}

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

I've also been able to get it to work using the @JsonIgnore annotation, but this solution isn't suitable for me.

我不明白为什么它在代码中工作但在配置中没有,所以任何帮助都会很棒。

I don't understand why it's working in code but not in the configuration, so any help would be fantastic.

推荐答案

从Jackson 2.0开始,您可以使用 JsonInclude

Since Jackson 2.0 you can use JsonInclude

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

这篇关于Spring REST服务:如何配置在json响应中删除空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆