Intro
This examples will demonstrates how to read JSON file using JSON Simple. To read a JSON file, you can use JSONParser class to read each of the values.
Examples
package com.freesamplecode.java.json.simple;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class ReadJSONFileDemo {
public static void main(String[] args){
JSONParser jsonParser = new JSONParser();
String fileName = "C:/TEMP/test.json";
try {
Object obj = jsonParser.parse(new FileReader(fileName));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
String country = (String) jsonObject.get("country");
System.out.println("Name : "+name);
System.out.println("Country : "+country);
System.out.print("Hobbies : ");
JSONArray jsonArray = (JSONArray) jsonObject.get("hobbies");
Iterator it = jsonArray.iterator();
while(it.hasNext()){
System.out.print(it.next()+", ");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Output
Name : Nursalim Country : Indonesia Hobbies : Reading, Coding, Traveling,

0 comments: