android Cursor to JSONArray

前端 未结 3 636
青春惊慌失措
青春惊慌失措 2021-02-14 21:52

how can I \"convert\" a Cursor to a JSONArray?

my cursor as 3columns (_id, name, birth)

I\'ve searched but I can\'t not find any examples

3条回答
  •  孤独总比滥情好
    2021-02-14 22:46

    private String cursorToString(Cursor crs) {
        JSONArray arr = new JSONArray();
        crs.moveToFirst();
        while (!crs.isAfterLast()) {
            int nColumns = crs.getColumnCount();
            JSONObject row = new JSONObject();
            for (int i = 0 ; i < nColumns ; i++) {
                String colName = crs.getColumnName(i);
                if (colName != null) {
                    String val = "";
                    try {
                        switch (crs.getType(i)) {
                        case Cursor.FIELD_TYPE_BLOB   : row.put(colName, crs.getBlob(i).toString()); break;
                        case Cursor.FIELD_TYPE_FLOAT  : row.put(colName, crs.getDouble(i))         ; break;
                        case Cursor.FIELD_TYPE_INTEGER: row.put(colName, crs.getLong(i))           ; break;
                        case Cursor.FIELD_TYPE_NULL   : row.put(colName, null)                     ; break;
                        case Cursor.FIELD_TYPE_STRING : row.put(colName, crs.getString(i))         ; break;
                        }
                    } catch (JSONException e) {
                    }
                }
            }
            arr.put(row);
            if (!crs.moveToNext())
                break;
        }
        crs.close(); // close the cursor
        return arr.toString();
    }
    

提交回复
热议问题