简体   繁体   中英

Read properties of array of json objects in a json file in java

I am new to JSON array/objects in the java. Here I am struggling to get the property of a JSON object. My attempt is as follows.

    JSONParser jsonParser = new JSONParser();
    try(FileReader reader = new FileReader("players.json")){                                     
       //Read JSON file                                  
       Object obj = jsonParser.parse(reader);                                                                
       JSONArray playersList = (JSONArray) obj; 
       //Below is the one which is having compilation issues                                                                 
       System.out.println(playersList.get(1).getString("name")); 

    } catch (FileNotFoundException e) {                                  
       // TODO Auto-generated catch block

           e.printStackTrace();
    } catch (IOException e) {                                    
       // TODO Auto-generated catch block

          e.printStackTrace();
     } catch (ParseException e) {                                    
       // TODO Auto-generated catch block                                    
          e.printStackTrace();
    }

There I am trying to get the name of the second object in the JSON array. But I couldn't find a way to call getString("name") as above. So I highly appreciate your help for this.

Json file is as follows.

      [
       {
         "_id": 1, 
         "name": "greg",
       },
       {
         "_id": 2,   
         "name": "freg gre",
       }
      ]

You can use like following

  JSONObject jsonObject = (JSONObject)playersList.get(1);
  String name = (String) jsonObject.get("name");
JSONParser jsonParser = new JSONParser();
    try(FileReader reader = new FileReader("players.json")){                                     

       Object obj = jsonParser.parse(reader);    
 JSONArray jsonArray = new JSONArray(obj);
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject json = jsonArray.getJSONObject(i);
        Iterator<String> keys = json.keys();

        while (keys.hasNext()) {
            String key = keys.next();
            System.out.println("Key :" + key + "  Value :" + json.get(key));
        }

    }

you just need to iterate through each object inside array and each object has keys and values fetch it within a loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM