JSONArray array = new JSONArray(string_of_json_array);

时间:2016-11-14 21:20:42

标签: java json parsing arraylist foreach

我正在尝试使用GSON和for循环解析Java中的Json arraylist(children)。 但我收到以下错误:

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代码让我知道我也会放置它而我之所以放置它的原因是因为它很长。所以怎么能我得到数组列表的孩子们显示?谢谢你的时间。

1 个答案:

答案 0 :(得分:0)

在Java对象中使用For-Each循环将要实现Iterable<T>接口。

要遍历children(正如您在评论中提到的那样),请使用:

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

List<T>实现了Iterable接口,因此您可以使用for-each循环。

了解详情:The For-Each LoopIterable