0

My code:

JSONObject data = {"result":{"a":[{"artist":"Aney","number:"1"},{"artist":"Aney","number:"2"}],"b":[{"artist":"Boney","number:"3"},{"artist":"Boney","number:"4"}], ....
JSONObject obj = new JSONObject(data.toString());
JSONArray tasks = obj.optJSONArray("result");

But tasks returns null.

I tried the below code but it did not work:

JSONObject data = {"result":{"a":[{"artist":"Money",...
JSONArray tasks = data.optJSONArray("result");

Update :

My main code is :

// get data from main url and reutnr array
JSONArray tasks = data.optJSONArray("result");
if(alert){
    // get data from another url and return object
    JSONObject data = {"result":{"a":[{"artist":"Money",...
    tasks = data.optJSONArray("result");
}

// now i use tasks in my code
if(tasks.length() > 0){
    ....
}
salari mameri
  • 228
  • 5
  • 13

2 Answers2

1

When you see "key": { ... }, that means key is a JSONObject.

When you see "key": [ ... ], that means key is a JSONArray.

In your case, "result" is a JSONObject, so write this instead:

JSONObject tasks = obj.optJSONObject("result");
Ben P.
  • 52,661
  • 6
  • 95
  • 123
  • @salarimameri well, the `results` object **isn't** an array, so you're going to have to clarify what you mean. – Ben P. Jul 04 '18 at 21:06
0

The JSONArray (a, b) is inside the object 'result' inside of the root object so you have to navigate the hyerarchy to get it:

JSONObject obj = new JSONObject(data.toString());
JSONObject result = obj.getJSONObject("result");
JSONArray tasksA = result.optJSONArray("a");
JSONArray tasksB = result.optJSONArray("b");

Note that each 'a' and 'b' is a different JSONArray to be retrieved.

Marcos Vasconcelos
  • 18,136
  • 30
  • 106
  • 167