Linda Linda - 4 months ago 8
JSON Question

Reading Json string from a JsonObject in android

I am having problems; I cannot read inner string from a jsonObject. It says JsonArray cannot be converted into JsonObject.

07-26 13:01:31.910 1798-1901/com.example.phuluso.aafs I/System.out: [{"AccommoAddress":{"AddressID":12,"City":"Johannesburg","InfoUrl":null,"Lattitude":"-26.181321","Longitude":"27.99158","PostalCode":2109,"Street":"22 Ararat Str","Town":"Westdene"},"AccommoDetails":null,"AccommoID":1,"AccommoImages":null,"AccommoName":"West Dunes Properties","AccommoType":"Flat","AccredStatus":"ACCREDITED","AddressId":12,"Capacity":9,"Distance":1,"EndDate":"2017-01-01","NearestCampus":"APK","OwnerId":0,"StartDate":"2016-01-01"}]


Here's my JsonArray. I am trying to read from AccommoAddress, but I get the error below:

[{"AccommoAddress":{"AddressID":12,"City":"Johannesburg","InfoUrl":null,"Lattitude":"-26.181321","Longitude":"27.99158","PostalCode":2109,"Street":"22 Ararat Str","Town":"Westdene"},"AccommoDetails":null,"AccommoID":1,"AccommoImages":null,"AccommoName":"West Dunes Properties","AccommoType":"Flat","AccredStatus":"ACCREDITED","AddressId":12,"Capacity":9,"Distance":1,"EndDate":"2017-01-01","NearestCampus":"APK","OwnerId":0,"StartDate":"2016-01-01"}]


Here's my code

@Override
protected void onPostExecute(String result) {

progressDialog.dismiss();
List<AccommoNearAPK> data = new ArrayList<>();
progressDialog.dismiss();

JSONObject jsonResponse = null;

try
{
jsonResponse = new JSONObject(result);
JSONArray jsonMainNode = jsonResponse.optJSONArray("AccommoAddress");

/*********** Process each JSON Node ************/

int lengthJsonArr = jsonMainNode.length();

for(int i=0; i < lengthJsonArr; i++)
{
/****** Get Object for each JSON node.***********/
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

/******* Fetch node values **********/
String name = jsonChildNode.optString("Street");
String number = jsonChildNode.optString("City");
String date_added = jsonChildNode.optString("Longitude");
String lat = jsonChildNode.optString("Lattitude");

System.out.print("Street"+ name + "City" +number+ "Long" + date_added+" Lat" + lat);

Toast.makeText(MapsActivity.this, date_added + name + number + lat, Toast.LENGTH_LONG).show();

}

} catch (JSONException e) {
Toast.makeText(MapsActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}

Answer

Your response is a JSONArray, not a JSONObject, similarly, AccommoAddress is a JSONObject, not a JSONArray. So you need to change the lines near the top to the following:

 JSONArray jsonResponse = null;

 try
 {
     jsonResponse = new JSONArray(result);
     JSONObject jsonMainNode = jsonResponse.optJSONObject("AccommoAddress");
Comments