Error reading Jsonobject inside an array

Asked

Viewed 91 times

4

I have the following JSON:

{  
   "setor":6,
   "tipo":"S",
   "filial":1,
   "peso":0,
   "doca":1,
   "operacao":1,
   "usuario":1,
   "empresa":1,
   "movimento":23,
   "local":4,
   "ativos":[  
      "{\"ativo\":1,\"quantidade\":25}",
      "{\"ativo\":2,\"quantidade\":33}"
   ]
}

The first data I read without difficulties, but the Array I’m not getting. I’m doing so:

JSONObject jsonObj = new JSONObject(json);

JSONArray c = jsonObj.getJSONArray("ativos");
for (int i = 0 ; i < c.length(); i++) {
    JSONObject obj = (JSONObject) c.get(i);  //aqui erro
    int ativo = obj.getInt("ativo");
    int quantidade = obj.getInt("quantidade");
}

Returns me error:

It’s not an Object

1 answer

4

The error occurs because this array has no JSON objects, but strings. All because of the quotes:

"ativos":["{\"ativo\":1,\"quantidade\":25}", "{\"ativo\":2,\"quantidade\":33}"]
          ^                               ^  ^                               ^

These quotes delimit a string, and within each string have a text which corresponds to an object (but not the object itself). Therefore, you should read the elements as strings, and from each string create a JSONObject:

JSONArray c = jsonObj.getJSONArray("ativos");
for (int i = 0; i < c.length(); i++) {
    // obter o elemento como String e criar um JSONObject
    JSONObject obj = new JSONObject(c.getString(i));
    int ativo = obj.getInt("ativo");
    int quantidade = obj.getInt("quantidade");
}

Of course this is a "gambiarra" to get around the problem of having a somewhat "strange" JSON. The ideal would be to fix the JSON at the source (where it is generated), so that it has an array of objects (i.e., without these quotes):

"ativos":[ {"ativo":1,"quantidade":25} , {"ativo":2,"quantidade":33} ]
          ^                           ^ ^                           ^
          não tem mais as aspas, agora são objetos (e não mais strings)

Then you could read it this way:

JSONArray c = jsonObj.getJSONArray("ativos");
for (int i = 0; i < c.length(); i++) {
    JSONObject obj = c.getJSONObject(i);
    int ativo = obj.getInt("ativo");
    int quantidade = obj.getInt("quantidade");
}

Browser other questions tagged

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