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

jackson, jax-rs, json

Solution

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);

Problem

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

Original source

Related problems