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

Java JSON Tutorial Content:

    JSON Introduction JSON.simple example-read and write JSON GSON example-read and write JSON Jackson example – read and write JSON Jackson Streaming API - read and write JSON
nbsp; 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"
package org.arpit.java2blog.pojo;

import java.util.ArrayList;
import java.util.List;

public class Country {

    String name;
    int population;
    private List<String> listOfStates;

    //getter and setter methods

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }

    public List<String> getListOfStates() {
        return listOfStates;
    }

    public void setListOfStates(List<String> listOfStates) {
        this.listOfStates = listOfStates;
    }

}

Write JSON to file:

Create a new class named "GSONWritingToFileExample.java" in src->org.arpit.java2blog
package org.arpit.java2blog;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.arpit.java2blog.pojo.Country;
import com.google.gson.Gson;

/*
 * @Author : Arpit Mandliya
 */
public class GSONWritingToFileExample {

 public static void main(String[] args) {

  Country countryObj=new Country();
  countryObj.setName("India");
  countryObj.setPopulation(1000000);
  List<String> listOfStates=new ArrayList<String>();
  listOfStates.add("Madhya Pradesh");
  listOfStates.add("Maharastra");
  listOfStates.add("Rajasthan");
  
  countryObj.setListOfStates(listOfStates);
  Gson gson = new Gson();
  
  // convert java object to JSON format,
  // and returned as JSON formatted string
  String json = gson.toJson(countryObj);
  
  try {
   //write converted json data to a file named "CountryGSON.json"
   FileWriter writer = new FileWriter("E:\\CountryGSON.json");
   writer.write(json);
   writer.close();
  
  } catch (IOException e) {
   e.printStackTrace();
  }
  
  System.out.println(json);
  
     }
}

Run above program and content of file CountryGSON.json will be as below :
{"name":"India","population":1000000,"listOfStates":["Madhya Pradesh","Maharastra","Rajasthan"]}

Read JSON to file:

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

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import org.arpit.java2blog.pojo.Country;
import com.google.gson.Gson;

/*
 * @Author : Arpit Mandliya
 */
public class GSONReadingFromFileExample {

 public static void main(String[] args) {

  Gson gson = new Gson();
   
  try {
  
   System.out.println("Reading JSON from a file");
   System.out.println("----------------------------");
   
   BufferedReader br = new BufferedReader(
     new FileReader("E:\\file.json"));
   
    //convert the json string back to object
   Country countryObj = gson.fromJson(br, Country.class);
   
   System.out.println("Name Of Country: "+countryObj.getName());

   
   System.out.println("Population: "+countryObj.getPopulation());

   System.out.println("States are :");
   
   List<String> listOfStates = countryObj.getListOfStates();
   for (int i = 0; i < listOfStates.size(); i++) {
    System.out.println(listOfStates.get(i));
   }
  
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}
Run above program and you will get following output:
Reading JSON from a file
----------------------------
Name Of Country: India
Population: 1000000
States are :
Madhya Pradesh
Maharastra
Rajasthan 

Project Structure: 

 

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

Java JSON Tutorial Content:

    JSON Introduction JSON.simple example-read and write JSON GSON example-read and write JSON Jackson example – read and write JSON Jackson Streaming API - read and write JSON

JSON.simple, is a simple Java library for JSON processing, read and write JSON data and full compliance with JSON specification (RFC4627).

In this post,we will read and write JSON using JSON.simple.
Download JSON.simple jar from here.
Create a java project named "JSONSimpleExample"
Create a folder jars and paste downloaded jar json-simple-1.1.1.jar.
right click on project->Property->java build path->Add jars and then go to src->jars->json-simple-1.1.1.jar.

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


Write JSON to file:

Create a new class named "JSONSimpleWritingToFileExample.java" in src->org.arpit.java2blog
package org.arpit.java2blog;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/*
 * @Author : Arpit Mandliya
 */
public class JSONSimpleWritingToFileExample {

    public static void main(String[] args) {

        JSONObject countryObj = new JSONObject();
        countryObj.put("Name", "India");
        countryObj.put("Population", new Integer(1000000));

        JSONArray listOfStates = new JSONArray();
        listOfStates.add("Madhya Pradesh");
        listOfStates.add("Maharastra");
        listOfStates.add("Rajasthan");

        countryObj.put("States", listOfStates);

        try {
            
            // Writing to a file
            File file=new File("E:\\CountryJSONFile.json");
            file.createNewFile();
            FileWriter fileWriter = new FileWriter(file);
            System.out.println("Writing JSON object to file");
            System.out.println("-----------------------");
            System.out.print(countryObj);

            fileWriter.write(countryObj.toJSONString());
            fileWriter.flush();
            fileWriter.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Run above program and you will get following output:
Writing JSON object to file
----------------------------
{"Name":"India","Population":1000000,"States":["Madhya Pradesh","Maharastra","Rajasthan"]}

Read JSON to file:

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

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/*
 * @Author : Arpit Mandliya
 */
public class JSONSimpleReadingFromFileExample {

 public static void main(String[] args) {

  JSONParser parser = new JSONParser();

  try {

   Object obj = parser.parse(new FileReader("E:\\CountryJSONFile.json"));

   JSONObject jsonObject = (JSONObject) obj;

   String nameOfCountry = (String) jsonObject.get("Name");
   System.out.println("Name Of Country: "+nameOfCountry);

   long population = (Long) jsonObject.get("Population");
   System.out.println("Population: "+population);

   System.out.println("States are :");
   JSONArray listOfStates = (JSONArray) jsonObject.get("States");
   Iterator<String> iterator = listOfStates.iterator();
   while (iterator.hasNext()) {
    System.out.println(iterator.next());
   }

  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (ParseException e) {
   e.printStackTrace();
  }

 }
}
Run above program and you will get following output:
Reading JSON from a file
----------------------------
Name Of Country: India
Population: 1000000
States are :
Madhya Pradesh
Maharastra
Rajasthan 

Project Structure: 

 

In this post,We will see introduction to JSON

Java JSON Tutorial Content:

    JSON Introduction JSON.simple example-read and write JSON GSON example-read and write JSON Jackson example – read and write JSON Jackson Streaming API - read and write JSON

What is JSON?

JSON stands for JavaScript Object Notation.It  is a simple and easy to read and write data exchange format just like XML.JSON is smaller than XML, and faster and easier to parse.

It is entirely language independent and can be used with most of the modern programming languages.

Internet media type of JSON is "application/json".

JSON sample:
    {
    "Countries": [
    { "Name": "India",
    "Capital": "Delhi"
    },
    {
    "Name": "France",
    "Major": "Paris"
    },
    ]
    } 
The above sample store informatipn about two countries.Basically
  1. Squiggly brackets({ }) act as containers
  2. Square brackets([ ]) represents arrays.
  3. Names and values are separated by a colon(:).
  4. Array elements are separated by commas

Comparison with XML:

As JSON and XML both are data exchange format.There is always comparison between them.

Similarity:
  • Both are human readable.
  • Both are hierarchical. (i.e. You can have values within values.)
  • Both are used by most of programming languages.
Differences:
  • JSON is less verbose so it's definitely quicker for humans to write, and probably quicker for us to read.
  • JSON stores data in form of Key-value pair which is universal in nature.
  • JSON is faster than XML.
  • JSON can be parsed trivially using the eval() procedure in JavaScript
 

Java tutorial for beginners Copyright © 2012