In this tutorials we are going to see how to read json data from file using JSONSimple jar.
Create project called JSONExample.
Create package called com.javatutorialscorner.json
Create java class called JSONExample under com.javatutorialscorner.json.
JSONExample.java
package com.javatutorialscorner.json;
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 JSONExample {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
JSONParser jsonParser = null;
try {
jsonParser = new JSONParser();
JSONObject json = (JSONObject) jsonParser.parse(new FileReader(
"C:\\jtc\\javatutorialscorner.json"));
String name = (String) json.get("name");
System.out.println("Name : " + name);
JSONArray jsonArray = (JSONArray) json.get("Topics");
System.out.println("JSON Array : " + jsonArray.toString());
Iterator<String> iterator = jsonArray.iterator();
while (iterator.hasNext()) {
System.out.println("JSON Array String : " + iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Now run the program see the following output in console.
Name : www.javatutorialscorner.com
JSON Array : ["Java","J2EE","Servlet","JSP","JSF","Struts","Spring","Hibernate"]
JSON Array String : Java
JSON Array String : J2EE
JSON Array String : Servlet
JSON Array String : JSP
JSON Array String : JSF
JSON Array String : Struts
JSON Array String : Spring
JSON Array String : Hibernate
0 comments:
Post a Comment