如何配置 spring mvc 3 在 json 响应中不返回“null”对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6049523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to configure spring mvc 3 to not return "null" object in json response?
提问by Bobo
a sample of json response looks like this:
json 响应示例如下所示:
{"publicId":"123","status":null,"partner":null,"description":null}
It would be nice to truncate out all null objects in the response. In this case, the response would become {"publicId":"123"}.
截断响应中的所有空对象会很好。在这种情况下,响应将变为{"publicId":"123"}。
Any advice? Thanks!
有什么建议吗?谢谢!
P.S: I think I can do that in Jersey. Also I believe they both use Hymanson as the JSON processer.
PS:我想我可以在泽西岛做到这一点。另外我相信他们都使用 Hymanson 作为 JSON 处理器。
Added Later: My configuration:
后来补充:我的配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Scans the classpath of this application for @Components to deploy as beans -->
<context:component-scan base-package="com.SomeCompany.web" />
<!-- Application Message Bundle -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages/messages" />
<property name="cacheSeconds" value="0" />
</bean>
<!-- Configures Spring MVC -->
<import resource="mvc-config.xml" />
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Configures the @Controller programming model -->
<mvc:annotation-driven />
<!-- Forwards requests to the "/" resource to the "welcome" view -->
<!--<mvc:view-controller path="/" view-name="welcome"/>-->
<!-- Configures Handler Interceptors -->
<mvc:interceptors>
<!-- Changes the locale when a 'locale' request parameter is sent; e.g. /?locale=de -->
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
</mvc:interceptors>
<!-- Saves a locale change using a cookie -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />
<!--<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="atom" value="application/atom+xml"/>
<entry key="html" value="text/html"/>
<entry key="json" value="application/json"/>
<entry key="xml" value="text/xml"/>
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingHymansonJsonView" />
<bean class="org.springframework.web.servlet.view.xml.MarshallingView" >
<property name="marshaller">
<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller" />
</property>
</bean>
</list>
</property>
</bean>
-->
<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
My code:
我的代码:
@Controller
public class SomeController {
@RequestMapping(value = "/xyz", method = {RequestMethod.GET, RequestMethod.HEAD},
headers = {"x-requested-with=XMLHttpRequest","Accept=application/json"}, params = "!closed")
public @ResponseBody
List<AbcTO> getStuff(
.......
}
}
回答by BennyFlint
Yes, you can do this for individual classes by annotating them with @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)or you can do it across the board by configuring your ObjectMapper, setting the serialization inclusion to JsonSerialize.Inclusion.NON_NULL.
是的,您可以通过使用注释来为单个类执行此操作,@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)或者您可以通过配置您的ObjectMapper,将序列化包含设置为JsonSerialize.Inclusion.NON_NULL.
Here is some info from the Hymanson FAQ: http://wiki.fasterxml.com/HymansonAnnotationSerializeNulls.
以下是 Hymanson 常见问题解答中的一些信息:http: //wiki.fasterxml.com/HymansonAnnotationSerializeNulls。
Annotating the classes is straightforward, but configuring the ObjectMapperserialization config slightly trickier. There is some specific info on doing the latter here.
注释类很简单,但配置ObjectMapper序列化配置稍微有点棘手。有做后者的一些具体的信息在这里。
回答by Mário Fernandes
Doesn't answer the question but this is the second google result.
不回答问题,但这是第二个谷歌结果。
If anybody comes here and wants do do it for Spring 4 (as it happened to me), you can use the annotation
如果有人来到这里并想为 Spring 4 做这件事(就像我遇到的那样),您可以使用注释
@JsonInclude(Include.NON_NULL)
on the returning class.
在返校班上。
As mentioned in the comments, and in case anyone is confused, the annotation should be used in the class that will be converted to JSON.
如评论中所述,如果有人感到困惑,则应在将转换为 JSON 的类中使用注释。
回答by Luís Soares
回答by Norbert
Java configuration for the above. Just place the below in your @Configuration class.
上面的Java配置。只需将以下内容放在您的 @Configuration 类中。
@Bean
public Hymanson2ObjectMapperBuilder objectMapperBuilder() {
Hymanson2ObjectMapperBuilder builder = new Hymanson2ObjectMapperBuilder();
builder.serializationInclusion(JsonInclude.Include.NON_NULL);
return builder;
}

