In this example we are going to use the JSON-Java (org.json) library to read or parse JSON file. First we start by getting the InputStream
of the JSON file to be read using getResourceAsStream()
method. Next we construct a JSONTokener
from the input stream and create an instance of JSONObject
to read the JSON entries.
We can use method like getString()
, getInt()
, getLong()
, etc. to read a key-value from the JSON file. The getJSONArray()
method allow us to read a list of values returned in JSONArray
object, which can be iterated to get each values represented by the key. Let’s see the detail code snippet below.
package org.kodejava.json;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.InputStream;
public class ReadJSONString {
public static void main(String[] args) {
// info.json
// {
// "id": "1",
// "name": "Alice",
// "age": "20",
// "courses": [
// "Engineering",
// "Finance",
// "Chemistry"
// ]
// }
String resourceName = "/info.json";
InputStream is = ReadJSONString.class.getResourceAsStream(resourceName);
if (is == null) {
throw new NullPointerException("Cannot find resource file " + resourceName);
}
JSONTokener tokener = new JSONTokener(is);
JSONObject object = new JSONObject(tokener);
System.out.println("Id : " + object.getLong("id"));
System.out.println("Name: " + object.getString("name"));
System.out.println("Age : " + object.getInt("age"));
System.out.println("Courses: ");
JSONArray courses = object.getJSONArray("courses");
for (int i = 0; i < courses.length(); i++) {
System.out.println(" - " + courses.get(i));
}
}
}
The result of the code snippet above is:
Id : 1
Name: Alice
Age : 20
Courses:
- Engineering
- Finance
- Chemistry
Maven Dependencies
<dependencies>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20240303</version>
</dependency>
</dependencies>
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Hi, I am trying the example you have given but getting an error at the line:
JSONTokener tokener = new JSONTokener(is);
And the error is below:
The constructor JSONTokener(InputStream) is undefined.
Can you please check and know which library you using?
Regards
Rohit
Hi Rohit,
I’m using the library as shown in the maven dependency section in the post above.
I had the same error but add the line below, it will work:
There is no such thing as ‘ReadJSONString’. Netbeans throws the fits.
ReadJSONString is the clas sname used in the example, you have to use your class name
Hi Wayan, Where do you place the file:
info.json
? I try relative path and absolute path and couldn’t find it.Hi Chao, I am placing the
info.json
file under theresources
directory (in a maven project structure). If you want to use absolute path you can do it like: