Problem when creating JSONObject in android studio

3

I am creating a login in Android Studio guiding me from a tutorial but I have been stuck, when creating a JSONObject there is something that fails and I do not know what it is. I have managed to create a String with the value of JSON and tried to create the JSON from the String but it has not yielded results.

But if I have managed to print this String and if it has the values I request. And I do not know what it is since it does not show me any error with which I can investigate.

My code is as follows:

public void verificar(JSONObject datos)
{
    try
    {
        String jresultado = datos.getString("resultado");
        if (jresultado.equals("true"))
        {
            JSONObject jdatos = new JSONObject(datos.getString("datos"));
            String u = jdatos.getString("user");
            String p = jdatos.getString("pwd");
            Toast.makeText(MainActivity.this, "Correcto Usuario: "+u+" / Pwd: "+p, Toast.LENGTH_SHORT).show();
        }
        else if(jresultado.equals("false"))
        {
            Toast.makeText(MainActivity.this, "Incorrecto", Toast.LENGTH_SHORT).show();
        }
        else
        {
            Toast.makeText(MainActivity.this, "Error de conexion", Toast.LENGTH_SHORT).show();
        }
    }
    catch (JSONException problema){problema.printStackTrace();}
}

NOTE:

This is the content that carries the JSONObject "data":

{"resultado":"true","datos":[{"user":"user","pwd":"9003d1df22eb4d3820015070385194c8"}]}

"datos" which is a JSONObject if it is full since I get the value of "result" but gets stuck when getting the content of "data"

    
asked by jose marquez 18.02.2018 в 00:36
source

1 answer

5

What happens is that the result is a String for which it has no problems, but datos is a array then it should parsear a JSONArray and then access the position that with getJSONObject and then to the property as he did with result.

 JSONArray datos = data.getJSONArray("datos");

 System.out.println(datos.getJSONObject(0).getString("pwd"));
 System.out.println(datos.getJSONObject(0).getString("user"));

This array of data may have more than 1 element, so it would be convenient to iterate over it with a% simple for maybe.

 for(int i = 0 ; i < datos.length() ; i++){
    System.out.println(datos.getJSONObject(i).getString("pwd"));
 }
    
answered by 18.02.2018 / 00:53
source