Android:数据库到 JSON

Android: Database to JSON

如何使用已填充的数据库生成 JSON 文件。截至目前,我一次只能检索它们 1 个。

例如,我有一个 table 的人,其中包含 ID、名字和姓氏。我怎样才能遍历所有这些人并最终得到一个包含所有人的 JSON 文件?

[
    {"id":1,"firstName":"Johnny","lastName":"Storm"},
    {"id":2,"firstName":"Sue","lastName":"Storm"},
    {"id":3,"firstName":"Reed","lastName":"Richards"},
    {"id":4,"firstName":"Ben","lastName":"Grimm"}
]

使用游标获取数据库中的所有数据然后使用

       JsonArray jsonArray = new JsonArray();
       cursor.moveToNext();
       while (cursor.moveToNext()) {
          JsonObject jsonObject=new JsonObject();
          jsonObject.put("id",cursor.getInt(cursor.getIndex(<your id column name>)))
       jsonObject.put("firstName",cursor.getString(cursor.getIndex(<your firstName column name>)))
         //Do same for all the other columns
        jsonArray.add(jsonObject);
      }

现在您的 JSONArray 将是 [{"id":1,"firstName":"Johnny","lastName":"Storm"},{"id":2,"firstName":"Sue","lastName":"Storm"},{"id":3,"firstName":"Reed", "lastName":"Richards"},{"id":4,"firstName":"Ben","lastName":"Grimm"}]