【发布时间】:2021-04-08 08:08:56
【问题描述】:
我正在尝试从 json 文件中获取数据并保存为对象,然后放入不同的 arrylist,我被困在我无法将“A320”放入对象中的点上,“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]
【问题讨论】:
-
看起来你正试图将 type_ratings 作为一个字符串,但你应该得到一个数组,就像你对飞行员做的那样。顺便说一句,您是否考虑过使用 gson 或 Jackson 之类的框架,或者您是否特别想手动执行此操作?
-
我想自己动手,请问有什么办法吗?
-
看起来你走对了路,我认为你只需要使用
pilot.getJSONArray("type_ratings")然后与你的方法保持一致,遍历它,然后在每个成员上调用 getString 。现在,如果每个飞行员都只有一个类型评级,您可以将其缩短为pil.setQualifiedFor(pilot.getJSONArray("type_ratings").getString (0)),但这假定没有空数组,并且只有一个以上的条目才会采用第一个条目。显然适应你的目的 -
是的,没有空的 arrys 值,您的方法有效,谢谢!!
-
太棒了,很高兴我能帮上忙——尽管我认为你很快就会破解它
标签: java arrays json object arraylist