Skip to content

How to read json file into java with simple JSON library

To read a JSON file into Java using the Simple JSON library, you can use the JSONObject class and the JSONArray class.

First, add the library dependency to your project. For Maven:

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

For Gradle:

groovy
implementation 'com.googlecode.json-simple:json-simple:1.1.1'

Ensure your data.json file contains valid JSON matching the expected structure:

json
{
  "name": "John Smith",
  "age": 30,
  "skills": ["Java", "Python"]
}

Here's an example of how you can read a JSON file into a Java object using the Simple JSON library:

java
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.FileReader;
import java.io.IOException;

public class Main {
  public static void main(String[] args) {
    // Create a JSON parser
    JSONParser parser = new JSONParser();

    try {
      // Read the JSON file and parse it
      Object obj = parser.parse(new FileReader("data.json"));

      // Convert the parsed object to a JSONObject
      JSONObject jsonObject = (JSONObject) obj;

      // Get the value of the "name" field
      String name = (String) jsonObject.get("name");
      System.out.println(name); // prints "John Smith"

      // Get the value of the "age" field
      long age = (long) jsonObject.get("age");
      System.out.println(age); // prints 30

      // Get the value of the "skills" field
      JSONArray skills = (JSONArray) jsonObject.get("skills");
      for (Object skill : skills) {
        System.out.println(skill); // prints "Java" and "Python"
      }
    } catch (IOException | ParseException e) {
      e.printStackTrace();
    }
  }
}

In this example, the JSONParser is used to parse the JSON file and create a Java object. The object is then cast to a JSONObject and the values of the various fields are extracted using the get() method. Note that get() returns Object and may return null if a key is missing, so consider adding null checks in production code.

Note: The org.json.simple library is unmaintained. For new projects, consider using modern alternatives like Jackson or Gson.

I hope this helps! Let me know if you have any questions.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.