GSON example – Read and write JSON

In this post,we will see how can we read and write JSON using GSON.

Java JSON Tutorial Content:

reading and writing JSON using json-simple.We will use another way(i.e. GSON) of reading JSON.
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.
There are various goals or advantages of using GSON(taken from GSON offcial page)

  • Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa
  • Allow pre-existing unmodifiable objects to be converted to and from JSON
  • Extensive support of Java Generics
  • Allow custom representations for objects
  • Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)

Reading and writing JSON using GSON is very easy.You can use these two methods:
toJSON() : It will convert simple pojo object to JSON string.
FromJSON() : It will convert JSON string to pojo object.
In this post,we will read and write JSON using GSON.
Download gson-2.2.4 jar from here.
Create a java project named “GSONExample”
Create a folder jars and paste downloaded jar gson-2.2.4.jar.
right click on project->Property->java build path->Add jars and then go to src->jars->gson-2.2.4.jar.

Click on ok.
Then you will see json-simple-1.1 jar added to your libraries and then click on ok

First create a pojo named “Country.java”

Write JSON to file:

Create a new class named “GSONWritingToFileExample.java” in src->org.arpit.java2blog

Run above program and content of file CountryGSON.json will be as below :

Read JSON to file:

Here we will read above created JSON file.
Create a new class named “JSONSimpleReadingFromFileExample.java” in src->org.arpit.java2blog

Run above program and you will get following output:

Project Structure:

7 Comments

  1. Raghav November 28, 2014
  2. Kedar January 20, 2015
  3. Jason February 11, 2015
  4. Muhammad Ali March 7, 2015
  5. ankita March 11, 2015
  6. websensepro April 23, 2015
  7. John September 24, 2015

Add Comment