We have uptaken Google GSON in our current project and have been trying to use it wherever JSON input/output is needed.
Google GSON is a Java Library that can convert any Java Object to JSON string and also form a Java Object from a JSON string.
The main advantage with using GSON is the plethora of options provided in the API which allows a bunch of customizations before converting an object to a JSON string.
One of the cases for Gson may be UI Messages. Server gets an AJAX call from browser it does the processing and want to send back a Status Message to the user. For this case we can have a small class
private String msgCode;
private String msgText; //translated msg Text
UIMessage(String msgCode, String msgText)
this.msgCode = msgCode;
this.msgText = msgText;
UIMessage msg = new UIMessage(“SAVE_SUCCESS”,”Updated Successfully”);;
Gson gson = new Gson();
String jsonMsg = gson.toJson(msg)
The above is the very simplistic use case with GSON. If you want to add more sophistications into it, you can start using the GsonBuilder class which is nothing but a Builder Pattern for Gson class.
By default GSON gives field name as key for the JSON text and field value as the value. In the above example the output will be like this
You have also option to control which field to serialize by using @Expose annotation (when used only serializes the fields marked with annotation) like
private String msgCode;
@Expose private String msgText; //translated msg Text
UIMessage msg = new UIMessage(“SAVE_SUCCESS”,”Updated Successfully”);
Gson gson = new GsonBuilder.excludeFieldsWithoutExposeAnnotation().create();
String jsonOutput = gson.toJson(msg);
In the above case it will just take msgText for serialization. Other way would be to mark certain fields as transient in the class and prevent it from being Serialized.
The biggest advantage I got with Gson apart from a flexible JSON conversion mechanism is that it promoted more OO within the system. Earlier we had messages and statuses floating around like raw Strings, now all of them have been encapsulated into its own class (like UIMessage above). Also the incoming JSON from the browser is also converted into equivalent Java Classes and these objects are further forwarded to Business Delegate Classes. Earlier the parameters were raw Strings floating around. Agreed we had the design all wrong in first place, but uptaking GSON made us create lot of classes interacting with HTTP Request and Business Logic and code is getting little better.