Read JSON array on Android

Asked

Viewed 715 times

4

I’m having trouble reading a JSON in the format:

[{"RESULTADO":"SUCESSO"}]

Webclient.java:

//PARA LER UM JSON, USAMOS A Scanner
        Scanner scanner = new Scanner (connection.getInputStream());
        String resposta = scanner.next();

        return resposta;

Logintask.java:

@Override
protected String doInBackground(ArrayList<Login>... params) {

    ArrayList<Login> result = params[0];

    String email = result.get(0).getEmail().toString();
    String senha = result.get(0).getSenha().toString();


    LoginConverter conversor = new LoginConverter();
    String json = conversor.converteParaJSON(email, senha);

    WebClient client = new WebClient();
    String resposta = client.post(json);



    return resposta;
}

@Override
protected void onPostExecute(String resposta) {

    //Toast.makeText(context, resposta, Toast.LENGTH_LONG).show();       


    Log.i("LOG", "Teste: " + resposta);
    //AQUI ESTÁ RETORNANDO DA SEGUINTE FORMA
    //[{"RESULTADO":"SUCESSO"}]


}

I need to take the value of "SUCCESS" to make a:

if (resposta.equals("SUCESSO")) {

        Toast.makeText(context, "LOGADO COM SUCESSO!", Toast.LENGTH_LONG).show();

    } else {


        Toast.makeText(context, "ERRO AO LOGAR!", Toast.LENGTH_LONG).show();
    }
  • You have to "parse" that text for objects. A good library for that is google gson. See tutorial below: https://medium.com/@ssaurel/parse-and-write-json-data-in-java-with-gson-a61f8772e786

3 answers

3


Your variable resposta contains all JSON content in one String:

[{"RESULTADO":"SUCESSO"}]

To transform this String in JSON objects, just use the package classes org.json.

If you look at JSON syntax, will see that the brackets ([ ]) delimit an array. In this case, the array contains only one element, which in turn is a Object, because it is enclosed by keys ({ }).

Then first we create the array, using the class JSONArray. Then we take the first element of the array, which will be a JSONObject:

String resposta = "[{\"RESULTADO\":\"SUCESSO\"}]";
// criar o JSONArray
JSONArray jsonArray = new JSONArray(resposta);
// pegar o primeiro elemento
JSONObject jsonObject = jsonArray.getJSONObject(0);

Now the jsonObject has the content {"RESULTADO":"SUCESSO"}. A Object is simply a set of several key/value pairs. In this case, we have only one key ("RESULTADO"), whose value is the string "SUCESSO". Then just take the value of this key and compare with the String that you want:

if ("SUCESSO".equals(jsonObject.getString("RESULTADO"))) {
    // sucesso
}
  • I’ve tried this Jsonarray jsonArray = new Jsonarray(reply); but it claims the following error "Jsonarray() in Jsonarray cannot be Applied to (java.lang.String)"

  • @Barraviera Vc is using the org.json.Jsonarray class?

  • 1

    Sorry, buddy. I was doing dumb and used the Jsonarray’s (with.google.gson). Now that I fixed it, it worked.

3

You can build something more object-oriented.

The idea is to have an object that represents the answer, with a field resultado. The return of the API (a String) would be mapped to this class, which would allow, with a simple getter, access the result. One of the main advantages of this approach is that it is extensible (i.e., if a new field appears in the response json, simply add to that class).

The class called Resposta, that mirrors your json:

class Resposta {
    private String resultado;

    public String getResultado() {
        return resultado;
    }

    public void setResultado(String resultado) {
        this.resultado = resultado;
    }

    public Resposta(String resultado) {
        this.resultado = resultado;
    }
}

In the method onPostExecute(String resposta), you could then do the Parsing of String received for an object of the type Resposta using an API called GSON, whose dependency can be downloaded here:

Gson gson = new Gson();
Resposta resp = gson.fromJson(resposta, Resposta.class);

At this point, just access resp.getResultado() and make your logic:

if ("SUCESSO".equals(resp.getResultado()) {
    // sua lógica de sucesso aqui
}
  • Good tip! Thanks! But I was having problems using Gson, but the idea of a class that mirrors json is a good one.

2

Now it worked by using Jsonarray from the org.json class.

try {

        JSONArray jsonArray = new JSONArray(resposta);

        JSONObject jsonObject = jsonArray.getJSONObject(0);

        if ("SUCESSO".equals(jsonObject.getString("RESULTADO"))) {

            Toast.makeText(context, "LOGADO COM SUCESSO", Toast.LENGTH_LONG).show();

        } else {

            Toast.makeText(context, "ERRO AO LOGAR", Toast.LENGTH_LONG).show();

        }


    } catch (JSONException e) {
        e.printStackTrace();
    }

Browser other questions tagged

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