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){
    ....
}
7
  • data.result is a JSON object, not an array Commented Jul 4, 2018 at 20:51
  • data = {"result": { ... }} Commented Jul 4, 2018 at 20:52
  • This post might be useful. Commented Jul 4, 2018 at 20:54
  • @LAD thank you. but my json code have very key and value. this is take time Commented Jul 4, 2018 at 21:01
  • 1
    then you have to parse it as an object and then go through each property adding to an array so that you get the structure you want Commented Jul 4, 2018 at 21:14

2 Answers 2

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

1 Comment

@salarimameri well, the results object isn't an array, so you're going to have to clarify what you mean.
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.

Comments

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.