Paulo Rodrigues Paulo Rodrigues - 1 year ago 147
JSON Question

ERROR in org.json.JSONException: of type org.json.JSONArray cannot be converted to JSONObject

StringRequest stringRequest = new StringRequest(
Request.Method.POST,
Configs.Login,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject obj = new JSONObject(response);
if(!obj.getBoolean("error")){

startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}else{
Toast.makeText(
getApplicationContext(),
obj.getString("message"),
Toast.LENGTH_LONG
).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();

Toast.makeText(
getApplicationContext(),
error.getMessage(),
Toast.LENGTH_LONG
).show();
}
}
)
@Override


I´m getting error in the JSON format that shows

org.json.JSONException: of type org.json.JSONArray cannot be converted to JSONObject

This is my JSON format

[{"id":"1","nome":"admin","email":"[email protected]","password":"xxxxxxx"}]

Answer Source

The JSON string you mentioned starts with "[" and ends with "]". That represents an array. JSON object starts with "{"and ends with "}".

You need to get rid of square brackets surrounding the JSON string. That would solve your issue.

If that's not possible, you can create JSONArray from the string and then use first item from it to get the properties such as name and email.

JSONArray jsonArray = new JSONArray(response);
JSONObject obj = jsonArray.getJSONObject(0);  

This should resolve your issue.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download