android_developer
android_developer

Reputation: 47

Convert SQLite to JSON

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.

Upvotes: 3

Views: 2689

Answers (3)

Kabir
Kabir

Reputation: 1489

Convert the data to String when you are storing

jsonObject.toString();

On retrieve you can get the json by converting the String.

JSONObject asdf = new JSONObject(<retrieved data>);

Upvotes: 1

Kamran Ahmed
Kamran Ahmed

Reputation: 7761

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

Upvotes: 2

mominapk
mominapk

Reputation: 81

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

Upvotes: 1

Related Questions