Thursday, October 27, 2011

How to create Type for ArrayList for GSon conversions?

I love GSON, mostly because it takes away lot of time we need to spend on parsing the JSON using the native JSON libraries. Its simlple, you create a object model for the JSON and gson can covert the JSON to a well defined object instance and vice versa.
This was easy. But i got struck when i added this custom java bean to a list and the tried to convert the JSON to a list of this Java bean. GSON will not understand the type of object under the list unless we specify it. This is how its done...
1) Define a type object (type object in under the reflection package)
Type type = new TypeToken>(){}.getType();
2) Use this type as an input during converion
gson.fromJson(jsonString,type);
This will give you the arraylist with the cutom java bean inside it.

No comments:

Post a Comment