JSON Java Example

Using Java, you can create desktop, web and mobile applications. In such applications, you might need to parse or generate JSON data. So this tutorial primarily focuses on how to generate and decode JSON using org.json package. This package contains important classes that help us to read and write JSON data in Java-

  • JSONObject- This class is used to generate key/value pair using put() method. The same class is also used to parse JSON data as well.
  • JSONArray- This class is used to generate JSON array.

How to install org.json package

To install org.json, you need to set classpath of json.rar or mention it in the Maven dependency.

  1. First of all, download json.jar file.
  2. Add Maven dependency by writing the following code in pom.xml file.
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20160810</version>
</dependency>

How to generate(encode) JSON in Java

To understand the generation of JSON, let's see a simple example-

import org.json.*;

public class Test{
   public static void main(String args[]){
      JSONObject obj = new JSONObject();
      String arr[] = {"black", "white", "grey"};
      JSONArray color = new JSONArray();
      obj.put("name", "Samsung Galaxy");
      obj.put("price", new Integer(15500));
      obj.put("color", color);
      System.out.println(obj);
   }
}

Output

{"price"15500:,"color":["black","white","grey"],"name":"Samsung Galaxy J7"}

How to parse(decode) JSON in Java

Let's take an example to understand the parse process of JSON-

import org.json.*;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Test{
   public static void main(String args[]) throws JSONException, IOException{
      BufferedReader reader = null;
      try {
	 URL url = new URL("http://tutorialsandyou.com/json/product.json");
	 reader = new BufferedReader(new InputStreamReader(url.openStream()));
	 StringBuffer buffer = new StringBuffer();
	 int read;
	 char[] chars = new char[1024];
	 while ((read = reader.read(chars)) != -1)
	    buffer.append(chars, 0, read); 

         JSONObject obj = new JSONObject(buffer.toString());
         System.out.println("Name: "+obj.get("name"));
         System.out.println("Description: "+obj.get("description"));
         System.out.println("Price: "+obj.get("price"));
         System.out.println("Sizes: "+obj.get("sizes"));
      }finally {
         if (reader != null)
            reader.close();
      }
   }
}

Output

Name: Reebok Athletic Shoes
Description: A pair of shoes that are designed for athletic championships
Price: 2000
Sizes: [6,7,8,9,10,11]