6

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

StaxMan
  • 113,358
  • 34
  • 211
  • 239
Bryan Young
  • 654
  • 4
  • 7
  • 23

2 Answers2

7

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);
StaxMan
  • 113,358
  • 34
  • 211
  • 239
  • 2
    Note that these methods are Jackson-only, and not vendor independent using JAX-RS. – Zero3 Jun 30 '15 at 14:18
  • Yes. There are few standardized configuration settings for JAX-RS, and no value class annotations as far as I know. – StaxMan Jul 08 '15 at 03:50
  • 2
    Specifying "include" in @JsonSerialize is now deprecated, one should instead use @JsonInclude(JsonInclude.Include.NON_NULL) – Nicola Ambrosetti Nov 25 '19 at 08:24
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.

Community
  • 1
  • 1
Piotr Kochański
  • 21,862
  • 7
  • 70
  • 77
  • 1
    Thanks. I was a little less than honest about my intentions. Truthfully, I started out with very clean static JSON while developing the client, but because most of the properties in the file are optional and rarely used, the version generated by the server was very large and ugly. You're probably right, that it isn't a real performance issue, but it is much more difficult to read than it could be. Thanks for the link. – Bryan Young Apr 27 '12 at 02:49