Problem when creating JSONObject in android studio


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)
        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();
            Toast.makeText(MainActivity.this, "Error de conexion", Toast.LENGTH_SHORT).show();
    catch (JSONException problema){problema.printStackTrace();}


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


"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

1 answer


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");


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++){
answered by 18.02.2018 / 00:53