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"}
In Jackson, we can use @JsonInclude(JsonInclude. Include. NON_NULL) to ignore the null fields.
In order to ignore null fields at the class level, we use the @JsonInclude annotation with include. NON_NULL.
Just add @JsonInclude annotation to classes not properties. Tested with and without this and it works.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With