-1

I'm trying to parse some JSON (excerpt below), but I receive the following error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    Can only iterate over an array or an instance of java.lang.Iterable

And an excerpt of the the very big json file :

[
  {
    "normal" : "Le tour change de sens ! Ce n'est pas une action, c'est le joker!"
  },
  {
    "normal" : "Prends la main de ton voisin de gauche"
  },
  {
    "normal" : "Fais une déclaration d'amour à la personne en face de toi!"
  },
  {
    "normal" : "Reste sur les genoux de la personne à ta droite pendant un tour"
  },

Figure it out by myself. Here's the code:

import org.json.simple.JSONArray;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.json.JSONException;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;


public class ParseJson{


    static String printAcounts = "";
    public static void main(String[] args) throws FileNotFoundException, IOException, ParseException, JSONException{
        JSONParser parser = new JSONParser();
        JSONArray objArray = (JSONArray) parser.parse(new FileReader("C:\\Users\\Bogdanel\\Desktop\\Ressources\\normal_actions.json"));

        for (Object o : objArray){
        JSONObject obj = (JSONObject) o;
        String s = (String) obj.get("normal");
        System.out.println(s);
        }


    }
}

ascasccascascasc

  • Which JSON library are you using? – nanofarad May 13 '16 at 20:15
  • The class `JSONArray` that you have does not implement `Iterable`, therefore you can't use Java's extended for-loop syntax. The solution will be to use the methods on `JSONArray`. For example if it has a length or size or count and a get method. This will depend on exactly which json library you are using. – dsh May 13 '16 at 20:19

2 Answers2

4

Don't confuse org.json.JSONArray and javax.json.JsonArray. The former does not implement Iterable while the latter does.

Android's use of JSONArray acts just like a typical JSON value except it can get(index) like a collection. JsonArray is basically a List<JsonValue>.

In short, use a typical for structure and use get instead.

Zircon
  • 4,677
  • 15
  • 32
0

JSONArray is not like a regular array, so you cannot iterate through it with a foreach loop (advanced for in Java). You can refer to this answer, but basically use a regular for loop and get items like this

objArray.getJSONObject(i).getString("someKey");
Community
  • 1
  • 1
Vucko
  • 7,371
  • 2
  • 27
  • 45