Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

We’ve all had this happen. There is a large model that is being converted to JSON, but only a few fields are populated. The result looks something like this

{
    "modelStatus": "ERROR",
    "message": null,
    "messages": [
    ],
    "previousPage": null,
    "nextPage": null,
    "redirect": false,
    "errors": [
    ],
    "errorFields": [
    ],
    "exception": null,
    "ssoToken": null,
    "bossUser": null,
    "idGame": 6067,
    "idAccount": 0,
    "currency": null,
    "language": null,
    "rgsCode": "aristocrat",
    "rgsGameId": "aris50Dragons",
    "tokenType": null,
    "tokenTtl": 0,
    "tokenModelAsJsonString": null,
    "channel": "pc",
    "clientType": "flash",
    "mode": "REAL",
    "clientUrl": "http://***URL with parameters removed***",
    "method": "GET",
    "contentType": null,
    "body": null,
    "status": "ERROR"
}

Jackson 2.0 (e.g. FasterXML) offers an annotation that can be used to tune the behavior of the JSON serializer. This is accomplished by placing a @JsonInclude annotation at the top of the model. There are several options.

NON_NULL can be used to tell FasterXML to not send any elements that are null.

@JsonInclude(JsonInclude.Include.NON_NULL)

This results in the same response appearing like…

{
    "modelStatus": "ERROR",
    "messages": [
    ],
    "redirect": false,
    "errors": [
    ],
    "errorFields": [
    ],
    "idGame": 6067,
    "idAccount": 0,
    "rgsCode": "aristocrat",
    "rgsGameId": "aris50Dragons",
    "tokenTtl": 0,
    "channel": "pc",
    "clientType": "flash",
    "mode": "REAL",
    "clientUrl": "http://***URL with parameters removed***",
    "method": "GET",
    "status": "ERROR"
}

Notice that there are several empty arrays. These can also be removed by specifying that only NON_EMPTY items are sent. To determine if something sould be included in the JSON, several methods are used:

  • null objects are not included
  • Collections and Maps – isEmpty() is called. The item is included if this returns false
  • Arrays – the length must be > than 0 for the array to be included
  • String – the length() is called. The string is included if the value is greater than 0.

This is accomplished by

@JsonInclude(JsonInclude.Include.NON_EMPTY)

August 21st, 2015

Posted In: Java, java ninja, Javaninja, javascript, json

Leave a Reply

Your email address will not be published. Required fields are marked *

WP to LinkedIn Auto Publish Powered By : XYZScripts.com