Friday, January 17, 2025
HomeTechHow to read json file into java with simple JSON library?

How to read json file into java with simple JSON library?

To read a JSON file in Java using the Simple JSON library, you can follow these steps. The Simple JSON library provides an easy-to-use API for parsing JSON data.

1. Add the Simple JSON Library to Your Project

Using Maven:

Add the following dependency to your pom.xml file:

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

Using Gradle:

Add this to your build.gradle:

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

If you’re not using a build tool, download the JAR file from Maven Repository and add it to your project manually.

2. Example JSON File

Let’s assume you have a JSON file named data.json:

{
  "name": "John Doe",
  "age": 30,
  "isEmployed": true,
  "skills": ["Java", "Python", "JavaScript"]
}

3. Code to Read and Parse the JSON File

Here’s how you can read and parse the JSON file using the Simple JSON library:

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

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

public class ReadJsonExample {
    public static void main(String[] args) {
        // Create a JSONParser instance
        JSONParser jsonParser = new JSONParser();

        try {
            // Read the JSON file
            FileReader reader = new FileReader("data.json");

            // Parse the JSON file into a JSONObject
            JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);

            // Extract data from the JSON object
            String name = (String) jsonObject.get("name");
            long age = (long) jsonObject.get("age");
            boolean isEmployed = (boolean) jsonObject.get("isEmployed");
            JSONArray skills = (JSONArray) jsonObject.get("skills");

            // Print the extracted data
            System.out.println("Name: " + name);
            System.out.println("Age: " + age);
            System.out.println("Is Employed: " + isEmployed);
            System.out.println("Skills: " + skills);

            // Close the reader
            reader.close();
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
    }
}

Explanation of the Code

  1. JSONParser:
    • The JSONParser class is used to parse JSON data into Java objects.
  2. FileReader:
    • Used to read the JSON file.
  3. JSONObject:
    • Represents the JSON object after parsing.
  4. Extracting Values:
    • Use the get method to retrieve values by their key.
    • For arrays, cast the value to a JSONArray.
  5. Exception Handling:
    • Handle IOException for file operations and ParseException for parsing errors.
See also  How to Switch Statement in C

Output

If data.json contains the provided JSON, the output will be:

Name: John Doe
Age: 30
Is Employed: true
Skills: [Java, Python, JavaScript]

Key Points

  • Ensure the file path (data.json) is correct.
  • If the JSON structure is complex (nested objects, arrays), you can cast values to JSONObject or JSONArray and iterate through them.
  • The Simple JSON library is lightweight and easy to use but lacks some features provided by modern libraries like Jackson or Gson.
See also  Difference between Operating system and Application

This is how you can read and parse a JSON file using the Simple JSON library in Java!

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x