Home » Core Java » json » Java JSON parser Example

About Katerina Zamani

Katerina Zamani
Katerina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she attends MSc courses in Advanced Information Systems at the same department. Currently, her main academic interests focus on web applications, mobile development, software engineering, databases and telecommunications.

Java JSON parser Example

JSON is a simply text format that facilitates reading and writing. It is a widely used data-interchange language because its parsing and its generation is easy for machines. In Java language there are some ways for JSON processing.

In this example we are going to use a common Java toolkit for JSONJSON.simple – and we will find out how to parse every type of a json file.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

1. Set the Environment

Before start coding we have to set a proper environment for the compiler, in order to recognize the JSON's classes. If you want to built your project via Maven, you should add the following dependency to your pom.xml:

<dependency>
	<groupId>com.googlecode.json-simple</groupId>
	<artifactId>json-simple</artifactId>
	<version>1.1</version>
</dependency>

Otherwise, you have to add the newest version of json-simple-1.1.1.jar in your CLASSPATH.

2. Example of JSON parsing

As we mentioned, we will show how we can parse a json file, so we will make our own .json file. This file is named jsonTestFile.json and has the next structure:

jsonTestFile.json:

{
  "id": 1,
  "firstname": "Katerina",
  "languages": [
    {
      "lang": "en",
      "knowledge": "proficient"
    },
    {
      "lang": "fr",
      "knowledge": "advanced"
    }
  ],
  "job": {
    "site": "www.javacodegeeks.com",
    "name": "Java Code Geeks"
  }
}

Now create a java file in your project, named JsonParseTest. Then paste the following code.

JsonParseTest.java:

package com.javacodegeeks.javabasics.jsonparsertest;

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;

public class JsonParseTest {

	private static final String filePath = "C:\\Users\\katerina\\Desktop\\jsonTestFile.json";
	
	public static void main(String[] args) {

		try {
			// read the json file
			FileReader reader = new FileReader(filePath);

			JSONParser jsonParser = new JSONParser();
			JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);

			// get a String from the JSON object
			String firstName = (String) jsonObject.get("firstname");
			System.out.println("The first name is: " + firstName);

			// get a number from the JSON object
			long id =  (long) jsonObject.get("id");
			System.out.println("The id is: " + id);

			// get an array from the JSON object
			JSONArray lang= (JSONArray) jsonObject.get("languages");
			
			// take the elements of the json array
			for(int i=0; i<lang.size(); i++){
				System.out.println("The " + i + " element of the array: "+lang.get(i));
			}
			Iterator i = lang.iterator();

			// take each value from the json array separately
			while (i.hasNext()) {
				JSONObject innerObj = (JSONObject) i.next();
				System.out.println("language "+ innerObj.get("lang") + 
						" with level " + innerObj.get("knowledge"));
			}
			// handle a structure into the json object
			JSONObject structure = (JSONObject) jsonObject.get("job");
			System.out.println("Into job structure, name: " + structure.get("name"));

		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		} catch (ParseException ex) {
			ex.printStackTrace();
		} catch (NullPointerException ex) {
			ex.printStackTrace();
		}

	}

}

Now lets explain the code above. After we create an instance of JSONParser, we create a JSONObject by parsing the FileReader of our .json file. This JSONObject contains a collection of key-value pairs, from which we can get every value of the json file. To retrieve primitive objects, get() method of the JSONObject's instance is called, defining the specified key as an argument. It is important to add the suitable cast to the method. For array types in json file, JSONArray is used that represents an ordered sequence of values. As you can notice in the code, an Iterator should be used in order to take each value of the json array. A structure in the json file, signs the creation of a new JSONObject in order to retrieve the values.

You can see the output of the execution below.

Output:

The first name is: Katerina
The id is: 1
The 0 element of the array: {"knowledge":"proficient","lang":"en"}
The 1 element of the array: {"knowledge":"advanced","lang":"fr"}
language en with level proficient
language fr with level advanced
Into job structure, name: Java Code Geeks

Download the source code

This was an example of JSON parsing in Java. Download the source code of this example: JsonParseTest.zip

Don’t forget to check out our Academy premium site for advanced Java training!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

 

Want to take your Java skills to the next level?

Grab our programming books for FREE!

Here are some of the eBooks you will get:

  • Spring Interview QnA
  • Multithreading & Concurrency QnA
  • JPA Minibook
  • JVM Troubleshooting Guide
  • Advanced Java
  • Java Interview QnA
  • Java Design Patterns