我有一个spring webservice,它返回一个json响应.我正在使用此处给出的示例来创建服务:http: //www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/
返回json的格式为:{"name":null,"staffName":["kfc-kampar","smith"]}
我想从返回的响应中删除任何空对象,所以它看起来像这样:{"staffName":["kfc-kampar","smith"]}
我在这里找到了类似的问题,但我已经能够得到一个解决方案,例如
如何在使用基于spring注释的配置时配置MappingJacksonHttpMessageConverter?
配置jacksonObjectMapper不能在spring mvc 3中工作
如何配置spring mvc 3在json响应中不返回"null"对象?
通过阅读这些和其他来源,我认为实现我想要的最简洁的方法是使用Spring 3.1和可以在mvc-annotation中配置的消息转换器.我更新的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>
Run Code Online (Sandbox Code Playgroud)
服务类与mkyong.com网站上的服务类相同,只是我注释了商店名称变量的设置,所以它是null,即
@Controller
@RequestMapping("/kfc/brands")
public class JSONController {
@RequestMapping(value="{name}", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public @ResponseBody Shop getShopInJSON(@PathVariable String name) …Run Code Online (Sandbox Code Playgroud)