Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert SQLite to JSON

Tags:

json

android

when i add data using SQLite is it possible to convert the data to JSON so that when I retrieve data it should be parsed and fetch data.If possible explain with example.

like image 820
android_developer Avatar asked Apr 15 '26 22:04

android_developer


2 Answers

When you fetch data from your SQLiteDatabase, it is returned in a Cursor. Unfortunately there's no such direct format to convert data from a cursor to JSON, but you can do it with some code like:

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;
}
like image 126
Kamran Ahmed Avatar answered Apr 17 '26 11:04

Kamran Ahmed


you can modify and use the following according to your need.

    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);

use this while storing your data

like image 27
mominapk Avatar answered Apr 17 '26 10:04

mominapk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!