Get JSONArray without array name?
You don't need to call json.getJSONArray()
at all, because the JSON you're working with already is an array. So, don't construct an instance of JSONObject
; use a JSONArray
. This should suffice:
// ...JSONArray json = new JSONArray(result);// ...for(int i=0;i<json.length();i++){ HashMap<String, String> map = new HashMap<String, String>(); JSONObject e = json.getJSONObject(i); map.put("id", String.valueOf(i)); map.put("name", "Earthquake name:" + e.getString("eqid")); map.put("magnitude", "Magnitude: " + e.getString("magnitude")); mylist.add(map); }
You can't use exactly the same methods as in the tutorial, because the JSON you're dealing with needs to be parsed into a JSONArray
at the root, not a JSONObject
.
I've assumed a named JSONArray is a JSONObject and accessed the data from the server to populate an Android GridView. For what it is worth my method is:
private String[] fillTable( JSONObject jsonObject ) { String[] dummyData = new String[] {"1", "2", "3", "4", "5", "6", "7","1", "2", "3", "4", "5", "6", "7","1", "2", "3", "4", "5", "6", "7", }; if( jsonObject != null ) { ArrayList<String> data = new ArrayList<String>(); try { // jsonArray looks like { "everything" : [{}, {},] } JSONArray jsonArray = jsonObject.getJSONArray( "everything" ); int number = jsonArray.length(); //How many rows have got from the database? Log.i( Constants.INFORMATION, "Number of ows returned: " + Integer.toString( number ) ); // Array elements look like this //{"success":1,"error":0,"name":"English One","owner":"Tutor","description":"Initial Alert","posted":"2013-08-09 15:35:40"} for( int element = 0; element < number; element++ ) { //visit each element JSONObject jsonObject_local = jsonArray.getJSONObject( element ); // Overkill on the error/success checking Log.e("JSON SUCCESS", Integer.toString( jsonObject_local.getInt(Constants.KEY_SUCCESS) ) ); Log.e("JSON ERROR", Integer.toString( jsonObject_local.getInt(Constants.KEY_ERROR) ) ); if ( jsonObject_local.getInt( Constants.KEY_SUCCESS) == Constants.JSON_SUCCESS ) { String name = jsonObject_local.getString( Constants.KEY_NAME ); data.add( name ); String owner = jsonObject_local.getString( Constants.KEY_OWNER ); data.add( owner ); String description = jsonObject_local.getString( Constants.KEY_DESCRIPTION ); Log.i( "DESCRIPTION", description ); data.add( description ); String date = jsonObject_local.getString( Constants.KEY_DATE ); data.add( date ); } else { for( int i = 0; i < 4; i++ ) { data.add( "ERROR" ); } } } } //JSON object is null catch ( JSONException jsone) { Log.e( "JSON EXCEPTION", jsone.getMessage() ); } dummyData = data.toArray( dummyData ); } return dummyData;
}