Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"}

like image 391
Bryan Young Avatar asked Apr 25 '12 15:04

Bryan Young


People also ask

How do I ignore null values in Jackson?

In Jackson, we can use @JsonInclude(JsonInclude. Include. NON_NULL) to ignore the null fields.

How do you ignore null values in JSON response Jax RS?

In order to ignore null fields at the class level, we use the @JsonInclude annotation with include. NON_NULL.

How do you remove null values from POJO?

Just add @JsonInclude annotation to classes not properties. Tested with and without this and it works.


2 Answers

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);
like image 108
StaxMan Avatar answered Oct 01 '22 13:10

StaxMan


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.

like image 36
Piotr Kochański Avatar answered Oct 01 '22 13:10

Piotr Kochański