如何 GSON/JSON 序列化一个 Android 游标?

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);

我的字符串 JSON 等于空 [] 因为 myCursor 没有正确序列化。

有什么建议吗?

   private static JSONArray cur2Json(Cursor cursor) {
    //
    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

您可以使用这段代码将1个游标数据直接转换为GSON对象 列名将用作键 列值将用作值

    Map hashMap = new HashMap();
    Gson gson = new Gson();
    for (int i = 0; i < cursor.getColumnCount(); i++) {
        hashMap.put(cursor.getColumnName(i),cursor.getString(i));
    }
    System.out.println(gson.toJson(hashMap));

如果你想转换多个游标元素你可以使用 arrayList 和 Map,然后将 arraylist 序列化为 String

    Gson gson = new Gson();
    ArrayList<Map> list = new ArrayList<>();
    while (!cursor.isAfterLast()) {
        Map hashMap = new HashMap();
        for (int i = 0; i < cursor.getColumnCount(); i++) {
            hashMap.put(cursor.getColumnName(i), cursor.getString(i));
        }
        list.add(hashMap);
        cursor.moveToNext();
    }
    System.out.println("\t\t\t" + gson.toJson(list));