biscuitstack biscuitstack - 5 months ago 40
JSON Question

Can't put JSONArray inside a JSONObject

As per this example, and others, I want to contain a

JSONArray
inside a named
JSONObject
. However:

JSONArray jsResultSet = new JSONArray();
...
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
for( int i=0 ; i< totalColumn ; i++ )
{
if( cursor.getColumnName(i) != null )
{
try
{
if( cursor.getString(i) != null )
{
rowObject.put(cursor.getColumnName(i) , cursor.getString(i) );
}
else
{
rowObject.put( cursor.getColumnName(i) , "" );
}
}
catch( Exception e )
{
Log.d("TAG_NAME", e.getMessage() );
}
}
}
jsResultSet.put(rowObject);
} while (cursor.moveToNext());
}

// Place JSONArray inside JSONObject
JSONObject jsCardsObj = new JSONObject();
jsCardsObj.put("cards", jsResultSet);


Is producing an exemption at the end in Android Studio, with the following line:

jsCardsObj.put("cards", jsResultSet);


Being reported that:

Unhandled exception: org.json.JSONException


I'm not sure what I'm doing differently than the example?

Answer

JSONObject.put throws JSONException.

You just need to surround jsCardsObj.put("cards", jsResultSet); with try/catch like this:

try{
    jsCardsObj.put("cards", jsResultSet); 
}catch(JSONException e){   
    //DO SOMETHING WITH EXCEPTION
}

Generally, if you have Unhandled exception you need to surround reported line with try/catch block.