Recognize a Jsonobject or Jsonarray

Asked

Viewed 1,493 times

3

I’m developing an app that consumes data from a Webservice, which can return one or more records at a time. Until the moment always received a Jsonarray, made the "conversion" of it:

JSONArray arrayDados = new JSONArray(dados);

However, when I receive only one object in this reply, how should I treat to avoid error in "conversion", since it is not a Jsonarray but a Jsonobject.

PS. Today I solved the archaic mode (to deliver), made a Try/except like a gohorse to be able to give continuity, and in exception, I call the treatment for Jsonobject:

JSONObject objectDados = new JSONObject(dados).
  • You can not at the time of sending JSON already be a list, even if it is with 1 object only?

  • It works, but, just change the place... I saw it in some places, and some people said: "test with Try/catch" and others said to use the "instaceof".

  • I have the same here, but when generating Json it is an array already with 0 element. Ai have no problems to do this, because I already know that every received object for conversion is a list

1 answer

2


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 Webservice, it is 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 an item or for N items.

What I would do, as 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 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 you can have other variables in JSON that save you trouble, for example, if there is no object in the database, return false in status and stop logic, return a message from the server, etc..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.