How to parse JSON in Java
In this Java tutorial, we are going to parse the JSON
data using java program. To parse the JSON object we need to add some extra jar/library. In this example, I am using JSON.simple to parse the objects. You can do this by other API like Gson or Jackson 2.
data.json
{
"founded":2016,
"name":"websparrow.org",
"articles":["java","struts","web"],
"location":"India"
}
Download the JSON.simple jar or add the maven/gradle dependency in your project.
pom.xml
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
build.gradle
compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
Check the full example
JsonParseExample.java
package org.websparrow;
import java.io.FileReader;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonParseExample {
public static void main(String[] args) {
JSONParser jsonParser = new JSONParser();
try {
Object object = jsonParser.parse(new FileReader("data.json"));
JSONObject jsonObject = (JSONObject) object;
// System.out.println(jsonObject);
long founded = (Long) jsonObject.get("founded");
System.out.println("founded: " + founded);
String location = (String) jsonObject.get("location");
System.out.println("location: " + location);
String name = (String) jsonObject.get("name");
System.out.println("name: " + name);
JSONArray articles = (JSONArray) jsonObject.get("articles");
Iterator itr = articles.iterator();
System.out.print("articles:");
while (itr.hasNext()) {
System.out.print(" " + itr.next());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
founded: 2016
location: India
name: websparrow.org
articles: java struts web