
What’s the best way to load a JSONObject from a json text file?
In this Java Example I’ll use the same file which we have generated in previous tutorial.
Maven Dependency:
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
Previous Tutorial: https://crunchify.com/how-to-write-json-object-to-file-in-java/
Sample JSON file content:
{
"Name": "crunchify.com",
"Author": "App Shah",
"Company List": [
"Compnay: eBay",
"Compnay: Paypal",
"Compnay: Google"
]
}
CrunchifyJSONReadFromFile.java
package crunchify.com.tutorials;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.FileReader;
import java.util.Iterator;
/**
* @author Crunchify.com
* How to Read JSON Object From File in Java?
*/
public class CrunchifyJSONReadFromFile {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("/Users/Shared/crunchify.json"));
// A JSON object. Key value pairs are unordered. JSONObject supports java.util.Map interface.
JSONObject jsonObject = (JSONObject) obj;
// A JSON array. JSONObject supports java.util.List interface.
JSONArray companyList = (JSONArray) jsonObject.get("Company List");
// An iterator over a collection. Iterator takes the place of Enumeration in the Java Collections Framework.
// Iterators differ from enumerations in two ways:
// 1. Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
// 2. Method names have been improved.
Iterator<JSONObject> iterator = companyList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Other must read: Create and Deploy simple Web Service and Web Service Client in Eclipse
Output:
Name: Crunchify.com Author: App Shah Company List: Compnay: eBay Compnay: Paypal Compnay: Google
I would recommend to use Maven’s pom.xml to add json-simple-1.1.1.jar
