Search code examples
androidserializationcursorgson

How to GSON/JSON serialize an Android Cursor?


import android.database.Cursor;
Cursor myCursor = mContentResolver.query(uri, null,..)
String JSON = new Gson().toJson(myCursor, Cursor.class);

My string JSON equals an empty [] because myCursor doesn't get serialized properly.

Any suggestions?


Solution

  •    private static JSONArray cur2Json(Cursor cursor) {
        //http://stackoverflow.com/questions/13070791/android-cursor-to-jsonarray
        JSONArray resultSet = new JSONArray();
        cursor.moveToFirst();
        while (cursor.isAfterLast() == false) {
            final int totalColumn = cursor.getColumnCount();
            JSONObject rowObject = new JSONObject(); 
            int i;// = 0;
            for (  i = 0; i < totalColumn; i++) {
    
                if (cursor.getColumnName(i) != null) {
                    try {
                        String getcol = cursor.getColumnName(i),
                               getstr = cursor.getString(i);
    
    
                        mLog.error("ColumnName(i):\t " + getcol + "\t: " + getstr);
                        rowObject.put(
                                    getcol,
                                    getstr 
                                     );
    
                    } catch (JSONException e) {
                        mLog.error( e.getMessage());
                    }
                }
            }//for
            mLog.error("columns i:\t " + i + "\totalColumn:\t " + totalColumn); 
            resultSet.put(rowObject);
            cursor.moveToNext();
        }
    
        return resultSet;
    }//cur2Json