-1

my json string is

String RESPONSE = "  { "Table": [] }  ";

and I use

 JSONObject jsonObj = new JSONObject(RESPONSE);
 JSONArray contacts = jsonObj.getJSONArray("Table");

Therefore, contacts = [] I mean empty. How can I control that array is empty. After this controller I use this command

JSONObject c = contacts.getJSONObject(0);

Of course is not empty :)

2
  • What do you mean "Of course is not empty"? Did you put something in it after your previous code where you obtained a clearly empty array? Commented Mar 13, 2017 at 17:57
  • if contacts is not empty continue Commented Mar 13, 2017 at 18:06

2 Answers 2

1

You can use length function:

JSONObject jsonObj = new JSONObject(RESPONSE);
JSONArray contacts = jsonObj.getJSONArray("Table");
if(contacts.length() > 0 ) {
    JSONObject c = contacts.getJSONObject(0);
}
Sign up to request clarification or add additional context in comments.

2 Comments

I've tried. Not working
what was happening, were you getting some error?
1

You could use the isNull() function.

JSONObject jsonObj = new JSONObject(RESPONSE);
JSONArray contacts = jsonObj.getJSONArray("Table");
if(!contacts.isNull(0)) {
   JSONObject c = contacts.getJSONObject(0);
}

10 Comments

No such function
Correct. Edited to show isNull.
No, Not working
contacts = " [ ] " ;
Have I miss understood the question? What do you mean by not working? are you saying contacts[0] is empty yet the if statement is still executing?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.