2015-11-11 37 views
0

從數據庫中的數據,我想檢索所有的數據庫,併爲每一行如和個人JSON:JSON在Android的

{ "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); 
} 

} 

我現在完全喪失和做不知道如何完成它。

回答

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數組英寸