How to access data from the innermost "level" of a JSON?

Asked

Viewed 873 times

6

I needed a way to access the innermost "level" of JSON below: (name, value, last query and source)

{
    "status": true,
    "valores": {
        "USD": {
            "nome": "Dólar",
            "valor": 2.333,
            "ultima_consulta": 1386349203,
            "fonte": "UOL Economia - http://economia.uol.com.br/cotacoes/"
        }
    }
}

I’m trying to access it this way, but he falls in JSONException:

   try {

        String resposta = ar.run(url); //resposta contém o JSON que retorna do WS
        Log.i("RETORNO: -------", resposta);
        JSONObject jo = new JSONObject(resposta);
        JSONArray ja;
        ja = jo.getJSONArray(resposta);
        moedas.setAbreviacao(ja.getJSONObject(0).getString("USD"));
        Log.i("RESULTADO: ", moedas.getAbreviacao());
        Log.i("RESULTADO: ", moedas.getDescricao());
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();;
    } finally {
        dialog.dismiss();

    }

I even tried to use GSON, but I was also unsuccessful.

1 answer

4


There is no array in JSON that you have - you only have objects (and primitive values - strings, numbers, etc). You will need to access them as such, something like the code below:

JSONObject jo = new JSONObject(resposta);
JSONObject valores = jo.getJSONObject("valores");
JSONObject usd = valores.getJSONObject("USD");
String nome = usd.getString("nome");
double valor = usd.getDouble("valor");
long ultimaConsulta = usd.getLong("ultima_consulta");
String fone = usd.getString("fone");
  • It worked. I just had to edit the line: JSONObject usd = jo.getJSONObject("USD"); for `Jsonobject usd = .getJSONObject("USD"); Thank you!

  • This - copy/Paste error. Fixed.

Browser other questions tagged

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