【问题标题】:Add json file into object and saved into arraylist将json文件添加到对象中并保存到arraylist
【发布时间】: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


【解决方案1】:

“type_ratings”键将返回 JSONArray,而不是 String。这是因为字符串周围有方括号,使其成为一个包含 1 个元素的数组。您可以更改 JSON 结构并删除方括号以使其仅成为字符串,或者您可以简单地执行pil.setQualifiedFor(pilot.getJSONArray("type_ratings")[0]);,这将获取数组并返回第一个元素,即字符串。请记住,只有当您知道 type_ratings 将始终包含一个包含 1 个字符串的数组时,您才应该这样做。

【讨论】:

    猜你喜欢
    • 2016-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 2018-10-29
    相关资源
    最近更新 更多