Ardi Abdul Ardi Abdul - 1 year ago 61
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

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) {
} finally {
if (br != null){

try {
} catch (IOException e) {


This is the Tree Class:

private String category;
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;
private String processedLang;
private String source;
private Tree tree;

public String getId() {
return id;

public void setId(String 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 Source

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()){             

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

Read more: The For-Each Loop, Iterable

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download