I have a String that I need to parse and it gives me the following error:
Value {"name":"test","code":"1","photo":"test"} at user of type org.json.JSONObject cannot be converted to JSONArray
the format of my json is as follows:
{"Error":false,"usuario":{"nombre":"prueba","codigo":"1","foto":"prueba"}}
and this is the code I have:
public void parseJson(String respuesta){
String nombre="d";
int codigo=0;
String foto="d";
try {
JSONObject jObject = new JSONObject(respuesta);
Boolean error = jObject.getBoolean("Error");
if (error){
String error_msg= jObject.getString("Error_msg");
Toast.makeText(getApplicationContext(),"Error: "+error_msg,Toast.LENGTH_LONG).show();
}else {
JSONArray jArray = jObject.getJSONArray("usuario");
JSONObject oneObject = jArray.getJSONObject(0);
nombre = oneObject.getString("nombre");
foto = oneObject.getString("foto");
codigo = oneObject.getInt("codigo");
String mensaje = "tu nombre es: " + nombre + ", tu codigo es: " + codigo + " y tu perfil es: " + foto;
Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error al parsear datos", Toast.LENGTH_SHORT).show();
Log.d("error parseando",e.getMessage());
}
}
I hope you can help me
The problem is that it
usuario
is an objectjson
, not an array . If you look at the format ofusuario
is the following:The format of a json array is as follows:
If you look closely, the values of an array are enclosed in curly braces
[]
and separated by commas, so you can easily tell what is an object and what is a json array.The correct way to get the values of the object
usuario
according to your json is the following:Check the structure of your json:
actually "user" is an object (remember Object: "{", array "[" ), and not an array, so this line will have the problem:
you should change to:
Code: