Jiayao Wang
Jiayao Wang

Reputation: 19

Add json file into object and saved into arraylist

enter image description hereI m trying get data from json file and saved as objects and then put into different arrylist, i m stuck on the point where i coundnt get "A320" into a obejcts, "type_ratings": [ "A320" ]

List<Crew> Allcrews = new ArrayList<>();
List<Pilot> pilotsList = new ArrayList<>();
List<CabinCrew> Cabincrews = new ArrayList<>();`
public void loadCrewData(Path p) throws DataLoadingException{
    try {
        BufferedReader reader = Files.newBufferedReader(p);
    
        String jsonStr = "";
        String line = "";
        while ((line=reader.readLine()) !=null) 
        {
            jsonStr =jsonStr+line;
            }
        System.out.println ("Pilots Informations: ");
        JSONObject jsonObj = new JSONObject(jsonStr);
        JSONArray pilots = jsonObj.getJSONArray("pilots");
            for(int j =0; j<pilots.length(); j++) {
                JSONObject pilot = pilots.getJSONObject(j);
                Pilot pil = new Pilot();
                pil.setForename(pilot.getString("forename"));
                pil.setHomeBase(pilot.getString("home_airport"));
                pil.setSurname(pilot.getString("surname"));
                pil.setRank(Rank.CAPTAIN);
                pil.setRank(Rank.FIRST_OFFICER);
                pil.setQualifiedFor(pilot.getString("type_ratings"));;
                
                pilotsList.add(pil);
                Allcrews.add(pil);
            
                
                System.out.println( "Forename: " +pilot.getString("forename"));
                System.out.println( "Surname: " +pilot.getString("surname"));
                System.out.println( "Rank: " +pilot.getString("rank"));
                System.out.println("Home_Airport: " + pilot.getString("home_airport"));
                System.out.println("type_ratings: " + pilot.getJSONArray("type_ratings"));  
 catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}[![JSONFile][1]][1]

Upvotes: 0

Views: 1084

Answers (1)

Sankeeth Ganeswaran
Sankeeth Ganeswaran

Reputation: 477

The "type_ratings" key will return a JSONArray, not a String. This is because of the square brackets that surround the string, making it an array with 1 element. You could either change the JSON structure and remove the square brackets in order to only make it a String, or you could simply do pil.setQualifiedFor(pilot.getJSONArray("type_ratings")[0]);, which will get the array, and return the first element, the string. Keep in mind that you should only do this if you know that type_ratings will always contain an array with 1 string.

Upvotes: 1

Related Questions