0

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)
Abra
  • 19,142
  • 7
  • 29
  • 41
  • it seems like the method cannot read and print out the data because it has more than one data in the JSON file... –  Jun 15 '21 at 07:44
  • Is the `>` really part of the JSON? Because that's not a valid format. And if it isn't, then the top-level element of your JSON is an array, not an object, so you need to loop over it's members and NOT call `parse` repeatedly. – Joachim Sauer Jun 15 '21 at 07:45
  • @Jansen Stanlie could it be that JSONObject is matching `{}` instead of `[]`? - can you try iterating a JSONArray instead? – thinkgruen Jun 15 '21 at 07:48
  • yes i'm using json simple –  Jun 15 '21 at 09:12

1 Answers1

2

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"));
}
bradley101
  • 723
  • 6
  • 19