如何从对象中提取多个json对象

如何从对象中提取多个json对象

问题描述:

我试图从json文件中读取剧集列表(http://epguides.frecar.no/show/bigbangtheory/),计算剧集标题并在控制台中打印它们。然而,因为我是新来的使用json,我甚至无法达到第一个标题,总是返回null。对正确的方向有一点帮助或一点小小的提示将不胜感激。如何从对象中提取多个json对象

JSONParser parser = new JSONParser(); 

try {  

    File tmpDir = new File("src/bigbangtheory.json"); 
    boolean exists = tmpDir.exists(); 
    if (exists==true) System.out.println("file exists"); 
    else System.out.println("file doesn't exist"); 

    Object obj = parser.parse(new FileReader("src/bigbangtheory.json")); 

    JSONObject season = (JSONObject) obj; 
    System.out.println(obj);    

    Object title = (Object) season.get("title"); 
    System.out.println(title);   

} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} catch (org.json.simple.parser.ParseException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 
+1

使用杰克逊解析器。可能会更容易:) – MarianP

JSON文件包含一个持有所有季节的对象。

从这个对象中,你需要提取特定的季节和情节,然后才能阅读标题。

Object obj = parser.parse(new FileReader("src/bigbangtheory.json")); 

JSONObject seasons = (JSONObject) obj; 
System.out.println(seasons); 

JSONArray seasonTwo = (JSONArray) seasons.get("2"); 
System.out.println(seasonTwo); 

for (Object o : seasonTwo) { 
    JSONObject episode = (JSONObject) o; 
    Object title = episode.get("title"); 
    System.out.println(title); 
}