java – Recognize a JSONObject or JSONArray


I'm developing an app that consumes data from a WebService, which in turn can return one or more records. Until now, it always received a JSONArray, "converted" it:

JSONArray arrayDados = new JSONArray(dados);

However, when I receive only one object in this response, how should I treat it so as not to give an error in the "conversion", since it is not a JSONArray, but a JSONObject.

PS.: Today I solved it in an archaic way (to deliver), I did a try/except like a gohorse to be able to continue, and in the exception, I call the treatment for JSONObject:

JSONObject objectDados = new JSONObject(dados).



You can identify if it's an object or array using the JSONToken:

Object json = new JSONTokener(data).nextValue();
if (json instanceof JSONObject)
  // Você tem um objeto
else if (json instanceof JSONArray)
  // Você tem um array

However, if you have access to the WebService, it's easier to return your data in an array, even with a single object, this way you can use the same logic.

Using JsonTokener you will have to do two logics, one to treat a single object and the other to treat a list of objects, if you always return an array, the treatment is the same for one item or for N items.

What would I do, as I even consider it a good practice, to send a Json Object with some control parameters and an array with the data:


And on Android you can always expect a Json Object containing a status and the data will always be in an array:

JSONObject objServerResponse = new JSONObject(strJsonServer); // <---- Sua String recebida
String status= objServerResponse.getString("status");
JSONArray arrayDados = objServerResponse.getJSONArray("dados");
   for (int i = 0; i < arrayDados.length(); i++) {
                      try {

                          JSONObject objItem= arrayDados.getJSONObject(i);
                          // faça algo com o objeto que você pegou

                       }catch(JSONException e){
                          return "Erro ao converter o JSON " + e;

This way you can implement the same logic, as long as you keep the same JSON pattern, and on top of that you can have other variables in the JSON that save you work, for example, if there is no object in the database, return false in the status and interrupt the logic, returning a message from the server, etc.

Scroll to Top