Read array JSON on Android

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 get the value of "SUCCESS" to make one:

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();
    }
    
asked by anonymous 04.12.2018 / 02:30

3 answers

3

Your variable resposta contains all JSON contents in String :

[{"RESULTADO":"SUCESSO"}]

To transform this String into JSON objects, simply use the package classes org.json .

If you look at the JSON syntax , you'll see that the brackets (% w / o%) delimit an array. In this case, the array contains only one element, which in turn is an object , since it is bounded by keys ( [ ] ).

Then we first created the array, using the class { } . Next, we get the first element of the array, which will be a JSONArray :

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

JSONObject now has content jsonObject . An object is simply a set of multiple key / value pairs. In this case, we only have a key ( {"RESULTADO":"SUCESSO"} ), whose value is the string "RESULTADO" . So just grab the value of this key and compare it to the "SUCESSO" you want:

if ("SUCESSO".equals(jsonObject.getString("RESULTADO"))) {
    // sucesso
}
    
04.12.2018 / 12:22
3

You can build something more object-oriented.

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

The class named Resposta , which 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 onPostExecute(String resposta) method, you could then do the parsing of the String received for an object of 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
}
    
04.12.2018 / 12:37
2

Now it works out using the JSONArray class org.json.

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();
    }
    
04.12.2018 / 15:36