9

如何将光标“转换”为 JSONArray?

我的光标为 3 列(_id、姓名、出生)

我已经搜索过,但找不到任何示例

4

3 回答 3

23

光标到 JSONArray

public JSONArray cur2Json(Cursor cursor) {

    JSONArray resultSet = new JSONArray();
    cursor.moveToFirst();
    while (cursor.isAfterLast() == false) {
        int totalColumn = cursor.getColumnCount();
        JSONObject rowObject = new JSONObject();   
        for (int i = 0; i < totalColumn; i++) {
            if (cursor.getColumnName(i) != null) {
                try {
                    rowObject.put(cursor.getColumnName(i),
                            cursor.getString(i));
                } catch (Exception e) {
                    Log.d(TAG, e.getMessage());
                }
            }
        }
        resultSet.put(rowObject);
        cursor.moveToNext();
    }

    cursor.close();
    return resultSet;

}
于 2014-09-28T11:42:52.420 回答
11
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();
}
于 2014-01-30T10:55:14.467 回答
4

您不能将游标的内容直接转换为 JSONObject,但您可以通过一些逻辑来做到这一点。

例如:从光标中检索字符串,形成一个遵循 JSON 格式的字符串,并使用它来创建一个 json 对象:

JSONObject jFromCursor=new JSONObject(string_in_JSON_format);
于 2012-10-25T14:32:08.820 回答