【问题标题】:convert sqlite data to json with gson使用 gson 将 sqlite 数据转换为 json
【发布时间】:2015-03-28 06:37:03
【问题描述】:

我想将 sqlite 数据制作成 jsonarray,但我遇到了一些问题 我已经编写了这段代码来使用 hasmap 从 sqlite 解析为 arraylist 并将其更改为 json 并使用 gson 进行转换

public ArrayList<HashMap<String, String>> tampil_semua_pesanan() {
    SQLiteDatabase database = this.getWritableDatabase();

    // deklarasikan sebuah arraylist yang bisa menampung hashmap
    ArrayList<HashMap<String, String>> arrayListBiodata = new ArrayList<HashMap<String, String>>();

    Cursor cursor = database.rawQuery("SELECT * FROM "+ TABLE_PESAN , null);

    // kursor langsung diarkan ke posisi paling awal data pada tabel_biodata
    if (cursor.moveToFirst()) {
        do {
            // deklarasikan sebuah hashmap, yang bisa menamp
            HashMap<String, String> hashMapBiodata = new HashMap<String, String>();

            hashMapBiodata.put("id", cursor.getString(0));
            hashMapBiodata.put("nama", cursor.getString(1));
            hashMapBiodata.put("jumlah", cursor.getString(2));

            // masukkan hashMapBiodata ke dalam arrayListBiodata
            arrayListBiodata.add(hashMapBiodata);

        } while (cursor.moveToNext());
    }
    cursor.close();
    return arrayListBiodata;
}

这就是解析它的方法

ArrayList<HashMap<String, String>> arrayListPesan = sqLiteHelper.tampil_semua_pesanan();
        userFunction.gson(arrayListPesan);
        Gson gson = new Gson();
        String jsonPesan = gson.toJson(arrayListPesan);

但我知道是这样的

[{"id":"11","jjumlah":"12","nama":"Ayam Goreng"},{"id":"11","jjumlah":"12","nama":"Ayam Goreng"},{"id":"11","jjumlah":"12","nama":"Ayam Goreng"}]

我想成为这样的人

["makanan":{"id":"11","jumlah":"12","nama":"Ayam Goreng"},{"id":"11","jumlah":"12","nama":"Ayam Goreng"},{"id":"11","jumlah":"12","nama":"Ayam Goreng"}]

谁能帮帮我

【问题讨论】:

标签: android json sqlite gson


【解决方案1】:

试试这个代码希望它可以工作......

    public ArrayList<HashMap<String, HashMap<String, String>>> tampil_meja() {
    SQLiteDatabase database = this.getWritableDatabase();
    ArrayList<HashMap<String, HashMap<String, String>>> arrayListMeja = new ArrayList<HashMap<String, HashMap<String, String>>>();

    Cursor cursor = database.rawQuery("SELECT * FROM "+ TABLE_MEJA , null);

    HashMap<String, HashMap<String, String>> hashMap = new HashMap<String, HashMap<String, String>>();
    if (cursor.moveToFirst()) {
        do {
            HashMap<String, String> hashMapBiodata = new HashMap<String, String>();
            hashMapBiodata.put("id", cursor.getString(0));
            hashMap.put("makanan", hashMapBiodata);
        } while (cursor.moveToNext());
    }
    cursor.close();

    arrayListMeja.add(hashMap);
    return arrayListMeja;
}

【讨论】:

    猜你喜欢
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多