我正在尝试检索所有数据库,并为每一行创建一个单独的JSON,例如:
{ "id":"1", "name":"John"}
{ "id":"2", "name":"Mick"}
{ "id":"3", "name":"Tom"}
这是我在DBQuery.java文件中的选择代码,用于获取用户:
public ArrayList<HashMap<String, String>> getUser(){
ArrayList<HashMap<String, String>>userArrayList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM user ORDER BY name";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
do{
HashMap<String, String> contactMap = new HashMap<String, String>();
contactMap.put("d", cursor.getString(0));
contactMap.put("name", cursor.getString(1));
userArrayList.add(contactMap);
} while(cursor.moveToNext());
}
return userArrayList;
}
到目前为止,这是我对JSON对象的代码:
public class user {
private String id;
private String name;
public user (String id, String name) {
this.name = id;
this.gender = name;
}
public String toJson() {
Gson gson = new Gson();
String json = gson.toJson(this);
return json;
}
public static user constructFromJson(String json) {
Gson gson = new Gson();
return gson.fromJson(json, user.class);
}
}
我现在完全迷失了,不知道如何完成它。
答案 0 :(得分:3)
我强烈建议您使用org.json.JSONObject,它简单可靠。 试试:
JSONArray jArray = new JSONArray();
while (cursor.moveToNext()) {
JSONObject jObject = new JSONObject();
jObject.put("id",cursor.getString(0));
jObject.put("name",cursor.getString(1));
jArray.put(jObject);
}
您将在json数组中拥有所有json db条目。