JSON.simple, is a simple Java library for JSON processing, read and write JSON data and full compliance with JSON specification (RFC4627).
downloaded jar json-simple-1.1.1.jar.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
/*
* @Author : Arpit Mandliya
*/
public class JSONSimpleWritingToFileExample {
public static void main(String[] args) {
JSONObject countryObj = new JSONObject();
countryObj.put("Name", "India");
countryObj.put("Population", new Integer(1000000));
JSONArray listOfStates = new JSONArray();
listOfStates.add("Madhya Pradesh");
listOfStates.add("Maharastra");
listOfStates.add("Rajasthan");
countryObj.put("States", listOfStates);
try {
File file=new File("E:\\CountryJSONFile.json");
file.createNewFile();
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(countryObj.toJSONString());
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
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;
/*
* @Author : Arpit Mandliya
*/
public class JSONSimpleReadingFromFileExample {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("E:\\CountryJSONFile.json"));
JSONObject jsonObject = (JSONObject) obj;
String nameOfCountry = (String) jsonObject.get("Name");
System.out.println("Name Of Country: "+nameOfCountry);
long population = (Long) jsonObject.get("Population");
System.out.println("Population: "+population);
System.out.println("States are :");
JSONArray listOfStates = (JSONArray) jsonObject.get("States");
Iterator<String> iterator = listOfStates.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}