【问题标题】:JSONArray array = new JSONArray(string_of_json_array);JSONArray 数组 = 新 JSONArray(string_of_json_array);
【发布时间】:2017-03-28 15:17:24
【问题描述】:

我正在尝试使用 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 代码,请告诉我我也会放置它,我没有放置它的原因是因为它很长。所以我怎么能得到要显示的数组列表子项?感谢您的宝贵时间。

【问题讨论】:

  • getCategory 返回一个字符串,但您试图在您的 for 循环中对其进行迭代。你想在这里完成什么?
  • 对不起,我忘了说..我正在尝试显示 Arraylist Children。

标签: java json parsing arraylist foreach


【解决方案1】:

要在要迭代的Java对象中使用For-Each循环,必须实现Iterable&lt;T&gt;接口。

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

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

List&lt;T&gt; 实现了 Iterable 接口,因此您可以使用 for-each 循环。

阅读更多:The For-Each LoopIterable

【讨论】:

  • 感谢您的回答,但是有没有办法让 Tree 类中的 Arraylist 显示出来?因为这可能会显示所有数组。 Child 只显示一个数组列表。
  • @ArdiAbdul 对不起,我不明白这一点。你想拥有什么?
猜你喜欢
  • 2023-03-22
  • 2014-06-09
  • 2017-10-04
  • 1970-01-01
  • 1970-01-01
  • 2014-10-05
  • 2011-06-14
  • 1970-01-01
  • 2017-03-09
相关资源
最近更新 更多