Recognize a JSONObject or JSONArray

2

I'm developing an app that consumes data from a WebService, which can return one or more records at a time. So far I've always been given a JSONArray, I'd "convert" it:

JSONArray arrayDados = new JSONArray(dados);

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

PS: Today I solved the archaic way (to deliver), I made a try / except like gohorse to be able to continue, and in the exception, I call JSONObject:

JSONObject objectDados = new JSONObject(dados).
    
asked by anonymous 13.07.2016 / 15:07

1 answer

1

Carlos,

You can identify if it is an object or array using 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 is easier to return your data in an array, even with a single object, so you can use the same logic.

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

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

{  
   "status":"true",
   "data":[  
      {  
         "id":"1"
      },
      {  
         "id":"2"
      },
      {  
         "id":"3"
      },
      {  
         "id":"4"
      }
   ]
}

And on Android you can always expect a Json Object containing a statuse 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;
                       }
   }

In this way you can implement the same logic, as long as you maintain the same JSON pattern, and above you can have other variables in JSON that save you work, for example, if there is no object in the database, return false in the status and interrupt logic, return a message from the server, etc.

    
13.07.2016 / 16:17