Wednesday, September 29, 2010

~~Java Object to Json and Vice Versa Using gson~~

A recent piece of work I completed took about three days of dreading. I wasn't sure how reflection in java could help me out.

Thanks to the connected world we live. All I had to get is a package called "gson" put out by google code community.

As I said, it was about three days of dreading and when the time came to finish it, I sat down and coded for exactly few minutes.

I had to send a json string built out of a list of custom object and to do it I wrote code similar to below:

//you can fill up the list with your custom objects
List<Object> customObjectList = new ArrayList<Object>();
//used gson-1.4.jar(freely available, no license needed)
Gson gson = new Gson();
//just one line as below, feed the list of your object and that's it
String internalOrderJSON = gson.toJson(objectList);

//it is just a simple string with json structure, still a string
//so it can be sent just like string to a server as in below
response.setContentType("text/plain");
response.getWriter().write(internalOrderJSON);

Ok..so the above was the easy part. Very plain and simple. But you know the world we live in, we give crap to somebody and lets say they put up with it, well the bad news is they will crap you back :)

Similarly, now whosoever I handed the json to, sent it back to me on the server side to convert it back to objects, to my persistant object and then persist it!!!

Oh well this is the part that I had dreaded originally.

But life was glorious again when I searched to find if java reflection was supported by the gson stack and Yes!! it was.

Ok, so implementation wise here is how you can do it.

//lets say the origin of the json string that you have is a http call
String jsonStringReceived = request.getParameter("someName");

//again get a reference to the Gson API.
Gson gson = new Gson();
//this one line is the magic, you tell Gson what type using reflection at run time
Type collectionType = new TypeToken<List<Object>>() {}.getType();
//and the following is not almost same as before
List<Object> yourCustomObjectList = gson.fromJson(jsonStringReceived, collectionType);
//your code to use the list of your object can go here


So, to summarize: all you need is a jar called gson-1.4.jar (at the time of this writing, gson-1.4.jar did the trick for me)

In addition to importing java's "reflection" package in your java class, you will need to import some other specific gson packages, but the following should be all you need if you plan to use the above technique:

import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
import com.google.gson.Gson;
get a copy of gson-1.4.jar for the above imports.

Thanks for stopping by and Happy Coding!
~Nirmal


Build a better mousetrap, and the world will beat a path to your door...
~Emerson