将SQLite转换为JSON

3
当我使用SQLite添加数据时,是否可以将数据转换为JSON,以便在检索数据时进行解析和获取数据。如果可能,请用示例说明。

你的意思是你正在将数据添加到数据库中,但当你取回它时,你希望它以JSON格式返回? - Kamran Ahmed
我的回答没有帮到你吗? - Kamran Ahmed
@PoojaNM,将JSON以字符串形式存储,例如:your_json.toString(),取回时从数据库获取字符串,然后转换为JSON对象,例如:JSONObject jobj = new JSONObject(your_string_from_database)。 - Hiren Patel
你可以接受一个回答或者发布自己的回答来解决你的问题。(那个在答案旁边的打勾按钮) - Kamran Ahmed
3个回答

2

当您从SQLiteDatabase中获取数据时,它会以Cursor的形式返回。不幸的是,没有直接的格式将光标中的数据转换为JSON,但您可以使用以下代码完成:

private JSONArray convertCursorToJSON(Cursor cursor) {
  JSONArray result = new JSONArray();

  int columnCount = cursor.getColumnCount();
  while (cursor.moveToNext()) {
    JSONObject row = new JSONObject();
    for (int index = 0; index < columnCount; index++) {
      row.put(cursor.getColumnName(index), cursor.getString(index));
    }
    result.put(row);
  }
  cursor.close();

  return result;
}

1
你可以根据需要修改和使用以下内容。
    Gson gson = new GsonBuilder().create();

    //wordList should be your arraylistdata or values etc which you want to insert 
    //Use GSON to serialize Array List to JSON
   gson.toJson(wordList);

使用此方法来存储您的数据。

1

在存储数据时,将其转换为字符串。

jsonObject.toString();

在检索时,您可以通过转换字符串来获取JSON。
JSONObject asdf = new JSONObject(<retrieved data>);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接