2016-11-14 111 views
0

我想解析Java中使用GSON和for循環的Json arraylist(children)。 但我收到以下錯誤:JSONArray array = new JSONArray(string_of_json_array);

for each not applicable to expression type 
required:array or java.lang.iterable 
found:String 

這裏是主要的Java類,顯示此錯誤

try { 
    br = new BufferedReader(new FileReader("user.json")); 
    Tree result = gson.fromJson(br, Tree.class); 

    if (result !=null){ 
     for (User t : result.getCategory()){ //ERROR IS HERE (squiggly red line) 
     System.out.println(t.getId() + "-" + t.getName() + "-" + t.getCategory() + "-" + t.getPercentage()); //ERROR IS ALSO HERE FOR EACH VARIABLES 
    } 
    } 


} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} finally { 
    if (br != null){ 

     try { 
      br.close(); 
     } catch (IOException e) { 
     e.printStackTrace(); 
     } 

    } 

這是樹類:

private String category; 
@SerializedName("children") 
@Expose 
private List<Child> children = new ArrayList<Child>(); 

public String getCategory() { 
return category; 
} 

public void setCategory(String category) { 
this.category = category; 
} 

public List<Child> getChildren() { 
return children; 
} 

public void setChildren(List<Child> children) { 
this.children = children; 
} 

用戶等級:

private String id; 
@SerializedName("processed_lang") 
@Expose 
private String processedLang; 
@SerializedName("source") 
@Expose 
private String source; 
@SerializedName("tree") 
@Expose 
private Tree tree; 

public String getId() { 
return id; 
} 

public void setId(String id) { 
this.id = id; 
} 

public String getProcessedLang() { 
return processedLang; 
} 

public void setProcessedLang(String processedLang) { 
this.processedLang = processedLang; 
} 

public String getSource() { 
return source; 
} 

public void setSource(String source) { 
this.source = source; 
} 

public Tree getTree() { 
return tree; 
} 

public void setTree(Tree tree) { 
this.tree = tree; 
} 
    String getName() { 
     throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. 
    } 

有人可以讓我知道我錯了什麼地方,如果你們想看到JSON代碼,讓我知道我也將它放置它,我沒有放置它的原因是因爲它很長。所以我怎麼能得到數組列出孩子要表演?謝謝你的時間。

+3

'getCategory'返回一個字符串,但你想遍歷它在你的'for'循環。你想在這裏完成什麼? – Zircon

+0

對不起,我忘了提及..我試圖展示Arraylist兒童。 –

回答

0

要在將要迭代的Java對象中使用For-Each循環必須實現Iterable<T>接口。

要通過children迭代(如你在評論中提及),只需使用:

for (Child child : result.getChildren()){    
    System.out.println(child); 
} 

List<T>實現Iterable接口的,所以你可以使用,每一個與它循環。

瞭解更多:The For-Each LoopIterable

+0

感謝您的回答,但有沒有辦法讓Arraylist從類樹中顯示出來?因爲這可能會顯示所有的數組。孩子只顯示一個數組列表。 –

+1

@ArdiAbdul對不起,我不明白這一點。你想要什麼? –