我的程序解析一个JSONArray,其中包含一个JSONObejcts列表,这些列表是飞行员。然后,它进行迭代并创建一个新的Pilot实例(继承自Crew超类),并将其添加到名为Crew类型的ArrayList中,称为loadedCrew(其类型为乘务员,因为乘务员也将添加到列表中)。
如下:
JSONObject crew = new JSONObject(json); //Create a new JSONObject called root from the json file stored in 'json'
JSONArray allPilots = crew.getJSONArray("pilots");
JSONArray allCabinCrew = crew.getJSONArray("cabincrew");
for (int i = 0; i < allPilots.length(); i++) {
Pilot a = new Pilot();
JSONObject pilot = allPilots.getJSONObject(i);
JSONArray typeRatings = pilot.getJSONArray("typeRatings");
a.setForename(pilot.getString("forename"));
a.setSurname(pilot.getString("surname"));
a.setHomeBase(pilot.getString("homebase"));
a.setRank(Pilot.Rank.valueOf(pilot.getString("rank")));
for(int i1=0; i1 < typeRatings.length(); i1++)
{
a.setQualifiedFor(typeRatings.getString(i1));
}
loadedCrew.add(a);
}
然后,一个单独的方法在loadedCrew列表中找到与条件匹配的对象时,应返回名为PilotOutput的Pilot(List)类型的输出列表。如下:
public List<Pilot> findPilotsByTypeRating(String typeCode) {
// TODO Auto-generated method stub
pilotOutput.clear();
for(Crew a : loadedCrew)
{
if (a instanceof Pilot && a.getTypeRatings().contains(typeCode));
{
pilotOutput.add((Pilot)a);
}
}
return pilotOutput;
}
但出现以下错误:
...引发异常:java.lang.ClassCastException:类baseclasses.CabinCrew无法转换为类baseclasses.Pilot
我不明白为什么会这样,因为不仅对象已经是Pilot类型,当我将其分配给输出列表时,我甚至将Pilot强制转换为它。我知道该方法不会尝试将任何CaberCrew添加到列表中,因为我已经使用System.out.print(a)来确保它仅获取试验对象。
有什么想法吗?谢谢。
删除if
行末的分号。应该是这样的:
if (a instanceof Pilot && a.getTypeRatings().contains(typeCode))
pilotOutput.add((Pilot) a);