0

I'm new to Java and I have a problem :

JSONObject data = new JSONObject(json);
List<String> list = (List<String>) data.getJSONArray("childrens");

for (String item : list) {
       Log.d("DEBUG", item);
}

I would like to assign data.getJSONArray("childrens") to a variable list, but I have an error:

java.lang.ClassCastException: org.json.JSONArray cannot be cast to java.util.List

How can I do this?

I would like to iterate over JSON Array.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
luthord
  • 3
  • 3
  • The error tells you exactly what the problem is, that the method `.getJSONArray(...)` returns an `org.json.JSONArray` object, **not** a `java.util.List` object, and casting the thing won't fix this. You need to create a JSONArray variable, assign to it the object returned from the method, and then use methods available to this object. – Hovercraft Full Of Eels Jun 17 '18 at 18:03
  • But how to iterate over JSONArray? – luthord Jun 17 '18 at 18:04
  • 1
    The [JSONArray API](https://developer.android.com/reference/org/json/JSONArray) will tell you what methods you can use with this, but I'd look at using the `length()` and `get(int index)` methods to iterate through using a for loop. – Hovercraft Full Of Eels Jun 17 '18 at 18:04
  • Use JSONArray list = data.getJSONArray("childrens"); – KayKay Jun 17 '18 at 18:05
  • Possible duplicate of [Converting JSONarray to ArrayList](https://stackoverflow.com/questions/17037340/converting-jsonarray-to-arraylist) – d.j.brown Jun 17 '18 at 18:05
  • You can iterate JSONArray just like any any array. for(int i = 0;i < list.length();++i){ String item = list.getString(i); } – KayKay Jun 17 '18 at 18:06
  • In the future, please search for and study the API before asking here. – Hovercraft Full Of Eels Jun 17 '18 at 18:08

2 Answers2

3

You can't data.getJSONArray("childrens") returns an object of type org.json.JSONArray.

However, you can iterate over a JSONArray :

    JSONArray jArray = data.getJSONArray("childrens");

    for (int i = 0; i < jArray.length(); i++) {
        JSONObject jb = jArray.getJSONObject(i);
        Log.d("DEBUG", jb);
    }
victor gallet
  • 1,819
  • 17
  • 25
1

JSONObject only contains JSONArray, not List. You have to transform it manually:

JSONObject data = new JSONObject(json);
JSONArray jsonArray = data.getJSONArray("childrens");
for (Object o : jsonArray) {
    String child = (String)o;
    Log.d("DEBUG", child);
}
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • @HovercraftFullOfEels [documentation](https://stleary.github.io/JSON-java/org/json/JSONArray.html) states it for *latest* version on 2016. – Luiggi Mendoza Jun 17 '18 at 18:08