Berikut adalah cara membaca file JSON / Parsing JSON dengan Java :
1. Buat File JSON : filebaca.json
{
"user-data" : {
"profile" : {
"name" : "Amir"
},
"address" : {
"road" : "Jl. Gunung Sahari",
"number" : "8"
},
"phone" : {
"mobile1" : 62851000011,
"mobile2" : 628510000012
}
}
}
2. Buat File Java untuk membaca : readjson.java
import java.io.FileReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
// @author Amir
public class ReadInfo {
public static void main(String[] args) {
JSONParser jp = new JSONParser();
try {
Object object = jp.parse(new FileReader("d\\filebaca.json"));
JSONObject jso = (JSONObject) object;
JSONObject userdata = (JSONObject) jso.get("user-data");
JSONObject profile = (JSONObject) userdata.get("profile");
JSONObject address = (JSONObject) userdata.get("address");
JSONObject phone = (JSONObject) userdata.get("phone");
String name = (String) profile.get("name");
String road = (String) address.get("road");
String number = (String) address.get("number");
Object mobile1 = phone.get("mobile1");
Object mobile2 = phone.get("mobile2");
System.out.println("name: "+name);
System.out.println("address: "+road+" "+number);
System.out.println("phone1: "+mobile1);
System.out.println("phone2: "+mobile2);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
3. Hasil jika dijalankan :
name: amir
address: jl. Gunung Sahari 8
phone1: 62851000011
phone2: 62851000012