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.

7
  • 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. Commented Jun 17, 2018 at 18:03
  • But how to iterate over JSONArray? Commented Jun 17, 2018 at 18:04
  • 1
    The JSONArray API 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. Commented Jun 17, 2018 at 18:04
  • Use JSONArray list = data.getJSONArray("childrens"); Commented Jun 17, 2018 at 18:05
  • Possible duplicate of Converting JSONarray to ArrayList Commented Jun 17, 2018 at 18:05

2 Answers 2

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);
    }
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

@HovercraftFullOfEels documentation states it for latest version on 2016.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.