【问题标题】:How to GSON/JSON serialize an Android Cursor?如何 GSON/JSON 序列化 Android 游标?
【发布时间】:2015-03-19 00:53:23
【问题描述】:
import android.database.Cursor;
Cursor myCursor = mContentResolver.query(uri, null,..)
String JSON = new Gson().toJson(myCursor, Cursor.class);

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

有什么建议吗?

【问题讨论】:

    标签: android serialization cursor gson


    【解决方案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
    

    【讨论】:

    • 这不是GSON 库!这个org.json。被提问者需要GSON
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      如果你想转换多个游标元素,你可以使用带有 Map 的 arrayList,然后将 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));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-11
        • 2022-01-01
        • 1970-01-01
        相关资源
        最近更新 更多