untuk membuat contoh membaca dan menulis file JSON dengan Java diperlukan library :
JSON Simple Library : json-simple.jar, library ini bisa di download pada salah satu link download ini
Berikut adalah cara read dan write file JSON menggunakan Java :
1. Write
1.1. Buat file WriteJson.java
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class WriteJson {
public static void main(String[] args) {
JSONObject obj = new JSONObject();
obj.put("nama", "Amir");
obj.put("sex", "Laki-Laki");
obj.put("umur", new Integer(23));
JSONArray listHobbies = new JSONArray();
listHobbies.add("Main Games");
listHobbies.add("Main Bola");
listHobbies.add("Melawak");
obj.put("hobi", listHobbies);
try {
FileWriter file = new FileWriter("d:\\filejson.json");
file.write(obj.toJSONString());
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(obj);
}
}
1.2. Jika dijalankan akan menghasilkan file JSON : fileJSON.json dengan isi
{"sex":"Laki-laki", "hobi":["Main Games", "Main Bola", "Melawak"],"nama":"Amir", "Umur":23}
2. Read
2.1. Buat file java untuk membaca JSON : ReadJson.java
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 ReadJson {
public static void main(String[] args){
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("d:\\filejson.json"));
JSONObject jsonObject = (JSONObject) obj;
String nama = (String) jsonObject.get("nama");
System.out.println("Nama = "+nama);
String gender = (String) jsonObject.get("sex");
System.out.println("Jenis Kelamin = "+sex);
long umur = (Long) jsonObject.get("umur");
System.out.println("Usia = "+umur);
System.out.println("Hobi = ");
// looping array hoby
JSONArray hobbies = (JSONArray) jsonObject.get("hobi");
Iterator iterator = hobbies.iterator();
while (iterator.hasNext()) {
System.out.println("\t - " + iterator.next());
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ParseException ex) {
ex.printStackTrace();
}
}
}
2.2. Jika dijalankan maka akan menampilkan :