Ardi Abdul Ardi Abdul - 24 days ago 9
JSON Question

JSONArray array = new JSONArray(string_of_json_array);

I am trying to parse Json arraylist(children) in Java using GSON and a for loop.
But I am getting the following error:

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


Here is the main Java Class which displays this error

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();
}

}


This is the Tree Class:

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;
}


User Class:

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.
}


Can someone let me know where I went wrong and if you guys want to see the json code let me know I will also place it and the reason I didn't place it is because its very long.So how can I get the array list children to show? Thanks for your time.

Answer

To use For-Each loop in Java object which is going to be iterated has to implement Iterable<T> interface.

To iterate through children (as you mentioned in the comment) just use:

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

List<T> implements Iterable interface so you can use for-each loop with it.

Read more: The For-Each Loop, Iterable