2016-11-14 109 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对不起,我不明白这一点。你想要什么? –