javajsonjson-simple

Parse Json Array java


i try to parse JSON array with format from file like this

> [
  {
    "Absensi": 20,
    "Tunjangan Makan": 400000,
    "name": "asdasd",
    "ID": 1,
    "Gaji Total": 5400000,
    "Gaji Pokok": 5000000,
    "email": [
      "asdasd",
      "asdas"
    ]
  },
  {
    "Absensi": 20,
    "Tunjangan Makan": 400000,
    "name": "jasnen",
    "ID": 2,
    "Gaji Total": 5400000,
    "Gaji Pokok": 5000000,
    "email": [
      "asdasd",
      "asdasda"
    ]
  }
]

here is my code:

public static void readJsonFileManager(String file) throws ParseException, FileNotFoundException, IOException{
    JSONParser parser = new JSONParser();
    Reader reader = new FileReader(file);

    Object jsonObj ;
    jsonObj =   parser.parse(reader);

    JSONObject jsonObject = (JSONObject) jsonObj;
    while(jsonObj != null) {
        long ID = (long) jsonObject.get("ID");
        System.out.println("ID = " + ID);
        String name = (String) jsonObject.get("name");
        System.out.println("Name = " + name);
        long Absensi = (long) jsonObject.get("Absensi");
        System.out.println("Absensi = " + Absensi);
        long GajiPokok = (long) jsonObject.get("Gaji Pokok");
        System.out.println("GajiPokok = " + GajiPokok);
        long GajiTotal = (long) jsonObject.get("Gaji Total");
        System.out.println("GajiTotal = " + GajiTotal);
        long Tunjangan = (long) jsonObject.get("Tunjangan Makan");
        System.out.println("Tunjangan Makan= " + Tunjangan + "\n");
        jsonObj =   parser.parse(reader);
    }

But when i run it it show error bracket on my terminal is there something wrong with my code, i cannot find any post relate to my problem??

Exception in thread "main" java.lang.ClassCastException: class org.json.simple.JSONArray cannot be cast to class org.json.simple.JSONObject (org.json.simple.JSONArray and org.json.simple.JSONObject are in unnamed module of loader 'app')
at com.company.DemoKerja.readJsonFileManager(DemoKerja.java:230)
at com.company.DemoKerja.main(DemoKerja.java:71)

Solution

  • Instead of taking it in JSONObject, parse it in JSONArray.

    JSONArray array = new JSONArray(jsonObject);
    
    while (array.hasNext()) {
        JSONObject obj = array.next();
        System.out.println(obj.get("ID"));
    }