martes, 16 de abril de 2013

Gson and how nice it is

Tired of Jackson are you?
Do you want to serialize a POJO and not have to add all those annotations?
Just want to try a different way to deal with Json?

The I have an answer for you: Google Gson.

Gson is the Google library to deal with JSON and serialization, but in a easier way.
For starters you don't need to use annotations for the properties or the methods, it uses (out of the box) the POJO convention and introspection to serialize the class.

So for example if you just want to serialize some Java class you have you'll have to do the following:
Gson gson = new GsonBuilder().create();
gson.toJson(anObject);

And to de-serialize it you'll do:
Gson gson = new GsonBuilder().create();
gson.fromJson(aJsonString, anObject.getClass());


Now one thing I just keep forgetting how to do (hence the name of the blog) is how to deserialize a plain old collections let say a List of Strings, and here is how:
 
import java.lang.reflect.Type;
Type type = new TypeToken<List<String>>() { }.getType();
List<String> aList =  new Gson().fromJson(jsonData, type);

As you can see it is quite simple to use, and of course this is just a really really really small port of what you can do with it, but it was a nice excuse for me to post how to deserialize a collection :P.  

For more information just check the Gson site here :

https://sites.google.com/site/gson/gson-user-guide

Any way I hope you can use it.
 

No hay comentarios:

Publicar un comentario