我想解析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代碼,讓我知道我也將它放置它,我沒有放置它的原因是因爲它很長。所以我怎麼能得到數組列出孩子要表演?謝謝你的時間。
'getCategory'返回一個字符串,但你想遍歷它在你的'for'循環。你想在這裏完成什麼? – Zircon
對不起,我忘了提及..我試圖展示Arraylist兒童。 –