Optimizing JaxRS/Jackson to exclude nulls, empty Lists, arrays

允我心安 提交于 2019-12-23 09:05:15

问题


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?

An example. JaxRS sends this:

{"prop1":[],"prop2":null,"prop3":"foo"}

where we could have gotten away with

{"prop3":"foo"}


回答1:


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.

It is also possible to configure this as the default behavior; in Jackson 1.9:

mapper.setSerializationConfig(mapper.getSerializationConfig().withSerializationInclusion(
  JsonSerialize.Inclusion.NON_EMPTY));

and in Jackson 2.0, bit simpler:

mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);



回答2:


First of all dropping properties from your JSON could lead to errors or unclear code on the client side - the client side has to check if a given property exists before using it, if the property is missing there would be JavaScript error reported. Boring stuff.

Since HTTP communication is gzipped, the potential gains from removing properties does not seem significant (I can be wrong, obviously - I don't know your application). GET request can be effectively cached, so one more reason to avoid such optimalization.

You can customize serialization of Java objects to JSON as you need. See this question How can I customize serialization of a list of JAXB objects to JSON? for further explanation how to do this.



来源:https://stackoverflow.com/questions/10318388/optimizing-jaxrs-jackson-to-exclude-nulls-empty-lists-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!