Home> Java> javaTutorial> body text

How can we read JSON file in Java?

WBOY
Release: 2023-08-30 09:53:05
forward
956 people have browsed it

JSONis one of the widely useddata exchangeformats and is alightweightand>language independent.json.simpleis a lightweight JSON processing library that can be used toreadandwriteJSON files, can be used toencodeordecodeJSON text, and is fully compliant with theJSON specification(RFC4627strong>). In order to read the JSON file, we need to download thejson-simple.jarfile 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 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(); } } }
Copy after login

Output

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

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!