Home >Java >javaTutorial >How can we read JSON file in Java?

How can we read JSON file in Java?

WBOY
WBOYforward
2023-08-30 09:53:051074browse

JSON is one of the widely used data exchange formats and is a lightweight and >language independent . json.simple is a lightweight JSON processing library that can be used to read and write JSON files, can be used to encode or decode JSON text, and is fully compliant with the JSON specification (RFC4627strong>). In order to read the JSON file, we need to download the json-simple.jar file and set the path to execute it.

json file

How can we read JSON file in Java?

Example

import java.io.*;
import java.util.*;
import org.json.simple.*;
import org.json.simple.parser.*;
public class JSONReadFromTheFileTest {
   public static void main(String[] args) {
      JSONParser parser = new JSONParser();
      try {
         Object obj = parser.parse(new FileReader("/Users/User/Desktop/course.json"));
         JSONObject<strong> </strong>jsonObject = (JSONObject)obj;
         String name = (String)jsonObject.get("Name");
         String course = (String)jsonObject.get("Course");
         JSONArray subjects = (JSONArray)jsonObject.get("Subjects");
         System.out.println("Name: " + name);
         System.out.println("Course: " + course);
         System.out.println("Subjects:");
         Iterator iterator = subjects.iterator();
         while (iterator.hasNext()) {
            System.out.println(iterator.next());
         }
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

Output

Name: Raja
Course: MCA
Subjects:
subject1: MIS
subject2: DBMS
subject3: UML

The above is the detailed content of How can we read JSON file in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete