How to convert java object to / from json format – (Gson API)
JSON is stand for JavaScript Object Notation, it is a lightweight data-interchange format. You can see many java applications throw away XML format and start using json as a new standard of data-interchange format. Java is all about object, often times, you need to convert an object into json format for data-interchange and vice verse.
In this artice, you will learn about the newly JSON library named Gson.
Gson is a Java library that can be used to convert Java Objects into its JSON representation
Gson is easy to learn and implement, what we need to know is the following two methods
1. toJson() – convert java object to JSON format
2. fromJson() – convert JSON into java object
1. toJson() example
import com.google.gson.Gson; class TestObjectToJson { private int data1 = 100; private String data2 = "hello"; } TestObjectToJson obj = new TestObjectToJson(); Gson gson = new Gson(); String json = gson.toJson(obj);
Output
Return String in json format {“data1″:100,”data2″:”hello”}
2. fromJson() example
import com.google.gson.Gson; class TestJsonFromObject { private int data1; private String data2; } String json = "{'data1':100,'data2':'hello'}"; Gson gson = new Gson(); TestJsonFromObject obj = gson.fromJson(json, TestJsonFromObject.class);
Output
Return an object (TestJsonFromObject) contains data1 (100) and data2 (hello).
Reference
1. Json Official site – http://www.json.org/
2. Json in Wiki – http://en.wikipedia.org/wiki/JSON
3. Google Gson – http://code.google.com/p/google-gson/
- Java Core Technology - Java RegEx, Java XML, Java I/O, Java Misc
- J2EE Frameworks - Hibernate, Spring 2.5, Spring MVC, Struts 1.x, Struts 2.x
- Build Tools - Maven, Archiva
- Unit Test - jUnit, TestNG
- Client Scripts - jQuery
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.