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.