How to convert Java object to / from JSON (Gson)
JSON is stand for JavaScript Object Notation, it is a lightweight data-interchange format. You can see many Java applications started to throw away XML format and start using json as a new s data-interchange format. Java is all about object, often times, you need to convert an object into json format for data-interchange or vice verse.
In this article, we show you how to use Gson, JSON library, to convert object to/from json.
Gson is easy to learn and implement, what we need to know are following two methods
- toJson() – Convert Java object to JSON format
- fromJson() – Convert JSON into Java object
1. Gson Dependency
For non-Maven user, get the Gson library from Gson official site, for Maven user, declares following dependency in your pom.xml.
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>1.7.1</version> </dependency>
2. POJO
A pojo, with initialized values. Later use Gson to convert this object to/from JSON formatted string.
package com.mkyong.core; import java.util.ArrayList; import java.util.List; public class DataObject { private int data1 = 100; private String data2 = "hello"; private List<String> list = new ArrayList<String>() { { add("String 1"); add("String 2"); add("String 3"); } }; //getter and setter methods @Override public String toString() { return "DataObject [data1=" + data1 + ", data2=" + data2 + ", list=" + list + "]"; } }
3. toJson() example
Convert object to JSON string, and save it as “file.json“.
package com.mkyong.core; import java.io.FileWriter; import java.io.IOException; import com.google.gson.Gson; public class GsonExample { public static void main(String[] args) { DataObject obj = new DataObject(); Gson gson = new Gson(); // convert java object to JSON format, // and returned as JSON formatted string String json = gson.toJson(obj); try { //write converted json data to a file named "file.json" FileWriter writer = new FileWriter("c:\\file.json"); writer.write(json); writer.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println(json); } }
Output
{"data1":100,"data2":"hello","list":["String 1","String 2","String 3"]}
4. fromJson() example
Read data from “file.json“, convert back to object and display it.
package com.mkyong.core; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import com.google.gson.Gson; public class GsonExample { public static void main(String[] args) { Gson gson = new Gson(); try { BufferedReader br = new BufferedReader( new FileReader("c:\\file.json")); //convert the json string back to object DataObject obj = gson.fromJson(br, DataObject.class); System.out.println(obj); } catch (IOException e) { e.printStackTrace(); } } }
Output
DataObject [data1=100, data2=hello, list=[String 1, String 2, String 3]]
You may interest at this – How to enable pretty print JSON output
References
- Google Gson – http://code.google.com/p/google-gson/
- Json Official site – http://www.json.org/
- Json in Wiki – http://en.wikipedia.org/wiki/JSON

Nice work! But, didn’t we need to close the reader as well after reading?
Hi,
This is really a great tutorial, but I have one Problem..
Person person = gson.fromJson( jsonResult, Person.class );
Person is a class created alos with serializedName and jsonRsult is a json String wha i Get from Webservice.
But this throws me an Exception
com.google.gson.stream.MalformedJsonException..
I am spendin more then 3 day but no solution..
Maybe the properties of Person don’t match your json
Thank you for your article addressing how to convert from a POJO to JSON and vice versa. But in the real world, it is more likely to convert JSON responses to a POJO that is not a direct mapping of JSON. So how can we approach this issue with Gson?
In that case you need to manually build the parser
Thanks for all the hard work and effort you put into your examples. I find the way you present your work to be easily understood and very helpful. More than once I have found the solutions to various problems from your site. Keep up the good work. Really great stuff.
In that case you need to manually build the parser
Thanx a lot for sharing your knowledge … im very happy that i found this tutorial…!
The
method is not needed. Gson structures its JSON output in the same way POJO is structured.
hello please, Do you have examples of GSON with google spreadsheet?
Hello
I’m have the problem with Hibernate and JSON
List listaTiendas = hibernateTiendaDAO.listar(“1″);
Gson gson = new GsonBuilder().serializeNulls().create();
System.out.println(gson.toJson(listaTiendas));
The error message is :
Exception in thread “main” java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?
at com.google.gson.internal.bind.TypeAdapters$1.write(TypeAdapters.java:64)
at com.google.gson.internal.bind.TypeAdapters$1.write(TypeAdapters.java:61)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ArrayTypeAdapter.write(ArrayTypeAdapter.java:93)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
at com.google.gson.Gson.toJson(Gson.java:586)
at com.google.gson.Gson.toJson(Gson.java:565)
at com.google.gson.Gson.toJson(Gson.java:520)
at com.google.gson.Gson.toJson(Gson.java:500)
at org.oplza.admin.services.impl.TiendaTest.listar(TiendaTest.java:51)
at org.oplza.admin.services.impl.TiendaTest.main(TiendaTest.java:27)
Awesome tutorial. Straight and to the point.
Here is how the post request string arrived to the server:
{“field3″:”333″,”field4″:{“field41″:”4111″,”field42″:”4222″,”field43″:”aaaa”}}
As you can see the field names are quoted which makes the gson.fromJson( fail…
what am i doing wrong … ajax call is sent this way:
$.ajax({
type: ‘POST’,
url: ‘SVLTRegister’,
dataType: “json”,
contentType: “application/json; charset=utf-8″,
data: JSON.stringify({field1:”111″,field2:”222″,field3:”333″,field4: {field41:”4111″,field42:”4222″,field43:”4333″}}),
You have helped me so much since I started to develop on android, thanks man. This works perfectly
I love you man, thanks…
hi,
i saw your tutorials it is very helpful.but 1 question in my mind.android provide json class to parsing purpose then what is the advantage of gson API over their .
This article is help full for me. Thank you very much!
Hey mykong,
Ihave one issue, i think u would be the better person to help me out..Actuallyi am parsing a json string but when the jsonobject takes the random json and i am converting tht to an xml it dont have the same format as parsed strign had it randomize the xml…
Nice.
But, it will be good if you can correct the exception handling. Doing a e.printStacktrace() is a terrible bad practice that starts in examples and inexperienced programmed get used to by copy&paste.
Experienced programmer should care about the message we communicate trough all of our code. Not just a matter on how to use certain API.
Regards!
Thanks a lot………..This helps me a lot
I wanted to learn about including jars in ant-generated jars, so I needed a simple example of code using a jar.
The example was great, because I could sling together a small but meaningful example from the code here.
On my other machine (in the shop at the moment) I have more complex Gson examples, including arrays, so I needed to find a quicky.
Thanks.
great simple example that clarifies it all!!!
thanks and don’t mind them “geniuses”..
when I have a collection, for example:
String json = “[{'data1':100,'data2':'hello'},{'data1':100,'data2':'hello'},{'data1':100,'data2':'hello'}]“;
how to transform I into an ArrayList?
Hi Danilo
The problem is that performing a
gson.fromJson(br, ArrayList.class)
wont’s work, as the ArrayList.class just returns ArrayList.
I know two solutions:
a) Instantiate the object
But I don’t like it too much as instatiating has a cost
b) create your list class:
First create a class for the list
public class DataObjects extends ArrayList {}
And then use this class:
I think this method makes clearer code and it’s useful if you new more methods in the collection (like search or classification functionalities)
There is a third method using a TypeToken, but I never use it and I don’t remember how it works. If anybody could help on it…
It is a dumb example… like the rest out there. Hardly anybody pulls json object-by-object. An example that shows how to pull an object array would be nicer.
@mkyong is there a way to run a java script on my site only for a particular country..
Like i want to run the code if the visitor is from Canada only and not from anywhere else.
Just add a if condition, what’s the problem?
can u show a example. it ll be very useful.
i m not a programmer and my friend needs it.
just a normal if statement, the biggest problem is how you know the visitor is from “Canada”? Usually it can determined by ip address, try google it.
This is a bit stupid since nobody uses such a simple datastructure.
your statement is too strong, this article is a very good start to demonstrate the use of Gson API.
Very rude and unhelpful comment…it’s an example from which you can gain an understanding and build more complex implementations…..jerk
He is just a spamster,easily figured by his name.Please Ignore him.
Thanks mykong for all the examples from the simple to toughest its actually the process that you have followed which made me understand all these technologies with ease.
Could you provide a sample with a more complex JSON?
One containing an json object with multiple arrays within it?
Hi,
can we convert Jquery object to string in java script????
i think you are in wrong topic. Btw refer here for your question http://stackoverflow.com/questions/652763/jquery-object-to-string
Does it work for private members of class also? Whats the implementation to get the value of a private field member defined in a class?
Gson can read private fields automatically and you don’t have to do anything with the class private fields.
Hi,
The last line from “2. fromJson() example”:
TestJsonFromObject obj = gson.toJson(json, TestJsonFromObject.class);
the “gson.toJson” should be “gson.fromJson”
hi,
Thanks for it, article updated accordingly.
Hi,I tried your example.
Reader br = new BufferedReader(new FileReader(“D:/…/…/file.json”));
DataObject object = gson.fromJson(br,DataObject.class);
System.out.println(object); // null..whats the problem here ?
Please ignore,that was a silly mistake.
Cheers :)