问题描述
我们正在使用JaxRS&杰克逊将数据发送给我们的客户。由于客户端是Javascript,如果没有该属性的有效值(默认情况下JaxRS默认),我们实际上不需要发送空值或空数组。有没有办法解决这个问题?
We're using JaxRS & Jackson to send data to our client. Since the client is Javascript, we don't really need to send null values or empty arrays if there isn't a valid value for that property (which JaxRS does by default). Is there a way around this?
一个例子。 JaxRS发送此信息:
An example. JaxRS sends this:
{prop1:[],prop2:null,prop3:foo }
我们可能已经离开了
{prop3:foo}
推荐答案
有多种方法可以实现这一目标,具体取决于:注释 @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
是单向的。或者,因为您还想删除空列表,数组,所以将NON_NULL更改为NON_EMPTY。
There are multiple ways to achieve this, depending; annotation @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
is one way. Or, since you also want to drop empty Lists, arrays, change NON_NULL to NON_EMPTY.
也可以将此配置为默认行为;在Jackson 1.9:
It is also possible to configure this as the default behavior; in Jackson 1.9:
mapper.setSerializationConfig(mapper.getSerializationConfig().withSerializationInclusion(
JsonSerialize.Inclusion.NON_EMPTY));
在Jackson 2.0中,更简单:
and in Jackson 2.0, bit simpler:
mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
这篇关于优化JaxRS / Jackson以排除空值,空列表,数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!