我试图从json文件中获取数据,并将其保存为对象,然后放入不同的arrylist中,我陷入了无法将“a320”放入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]
1条答案
按热度按时间t5fffqht1#
“typeu ratings”键将返回jsonarray,而不是字符串。这是因为字符串周围有方括号,使其成为一个包含1个元素的数组。您可以更改json结构并删除方括号,使其成为字符串,也可以简单地执行以下操作
pil.setQualifiedFor(pilot.getJSONArray("type_ratings")[0]);
,它将获取数组,并返回第一个元素字符串。请记住,只有当您知道type\u ratings将始终包含一个带有1个字符串的数组时,才应该这样做。