android object to json,android Cursor to JSONArray

问题

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

回答1:

You can't convert the contents of a cursor directly into a JSONObject, but you can do that with some logic.

for eg: retrieve the Strings from the cursor, form a String which follows the JSON format, and use it to make a json object :

JSONObject jFromCursor=new JSONObject(string_in_JSON_format);

回答2:

Cursor to 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;

}

回答3:

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

}

来源:https://stackoverflow.com/questions/13070791/android-cursor-to-jsonarray

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值