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.
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.
[...] retrieved from: How to convert Java object to / from JSON (Gson) [...]
[...] messages=[msg 1, msg 2, msg 3]]ReferencesDownload JacksonJackson Official SiteGson example – convert Java object to / from JSON [...]
[...] tutorial, we show you how to enable pretty print JSON output in Gson framework. In last Gson – object to/from json example : Gson gson = new Gson(); String json = gson.toJson(obj); [...]
great simple example that clarifies it all!!!
thanks and don’t mind them “geniuses”..
[...] LinkedIn [...]
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.