2015-03-19 33 views
0
import android.database.Cursor; 
Cursor myCursor = mContentResolver.query(uri, null,..) 
String JSON = new Gson().toJson(myCursor, Cursor.class); 

我的字符串JSON等於空[],因爲myCursor沒有正確序列化。GSON如何序列化Android遊標?

有什麼建議嗎?

回答

1
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 
0

您可以使用這段代碼轉換成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)); 
0

,如果你想轉換多個遊標元素你可以使用一個arrayList與Map然後串行化Arrayyl到字符串

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