Serializing/Deserializing Json in GWT
JSON & GWT
There was recently an interesting discussion in GWT Users group about best practices for serializing/deserializing JSON in the client side. This post aims to highlight its important points. There is so far three different ways of converting an object to JSON and back from the client side in GWT:
gwt-jackson wraps some of the functionalities of the famous Jackson Library. It allows converting an object using an interface called ObjectMapper. The advantage of using gwt-jackson is that it takes care of serializing complex Objects such as Collections and Maps. It also allows fancy conversion using annotations such as @JsonProperty, and @JsonCreator. The only bummer of gwt-jackson is that it uses Generators which will be deprecated in the version 3.0 of GWT. It’s also worth noting that gwt-jackson is used by RestyGWT which is one of alternatives for making HTTP Requests from the client side.
Examples can be found in the Github Page: https://github.com/nmorel/gwt-jackson/tree/master/examples
using JsInterop annotations:
if our object looks like:
JsInterop is used by autorest-gwt, which is also one of the options for making HTTP calls, to serialize/serialize objects prior to making HTTP requests.
It is important to note that Maps are not handled by JSON.stringify() method, an attempt to stringify a Map throws the following error:
Uncaught TypeError: Converting circular structure to JSON
Converting a Collection such as an ArrayList does not throw any error, but creates additional JSON fields that the developper would want to get rid of:
The “array_3_g$” is added by GWT compiler for some reason, so the user needs to find a way to remove it for a clean conversion like:
Plain Arrays is the only structure that is converted properly, so far.
Out of the three methods, JsInterop seems the most viable method for handling JSON. The main concern for now is handling objects such as Collections and Maps which require some further manual processing by the developer. Plain Arrays is the only structure that is converted properly for now, so developers can try to simplify or convert to Plain Arrays for a clean conversion.