I am new to json. I am trying to get two Sqlite tables into a json text file. I am able to fetch each table and send to text file but my results are invalid if I try to read the string from the file.
Here is the code:
File f = new File(Constants.DEFAULT_BACKUP_FILE_PATH);
FileOutputStream fos = new FileOutputStream(f,true);
PrintStream ps = new PrintStream(fos);
String query1 = "SELECT " + COL_1 + "," + COL_2 + " FROM " + TABLE_1;
Cursor cursor1 = db.rawQuery(query1, null);
cursor1.moveToFirst();
JSONObject mObject = new JSONObject();
JSONArray tab1Array = new JSONArray();
int i = 0;
while (!cursor1.isAfterLast()) {
JSONObject rObject = new JSONObject();
try {
rObject.put("id", cursor1.getString(cursor1.getColumnIndex(COL_1)));
rObject.put("user", cursor1.getString(cursor1.getColumnIndex(COL_2)));
cursor1.moveToNext();
tab1Array.put(i, rObject);
i++;
} catch (JSONException e) {
e.printStackTrace();
}
}
mObject.put("TABLE1", tab1Array);
ps.append(mObject.toString());
String query2 = "SELECT " + COL_1 + "," + COL_2 + " FROM " + TABLE_2;
Cursor cursor2 = db.rawQuery(query2, null);
cursor2.moveToFirst();
JSONObject mObject2 = new JSONObject();
JSONArray tab2Array = new JSONArray();
int i2 = 0;
while (!cursor2.isAfterLast()) {
JSONObject rObject2 = new JSONObject();
try {
rObject2.put("id", cursor2.getString(cursor2.getColumnIndex(COL_1)));
rObject2.put("name", cursor2.getString(cursor2.getColumnIndex(COL_2)));
cursor2.moveToNext();
tab2Array.put(i2, rObject2);
i2++;
} catch (JSONException e) {
e.printStackTrace();
}
}
mObject2.put("TABLE2", tab1Array);
ps.append(mObject2.toString());
My text file looks like this (note no comma between the two):
{"TABLE1":[{"id":"1", "user":"Larry"},{"id":"2", "user":"Mo"},{"id":"4", "user":"Curly"},{"id":"5", "user":"Shemp"}]} {"TABLE2":[{"id":"1", "name":"Ticky"},{"id":"2", "name":"Tky"},{"id":"4", "name":"Tem"},{"id":"5", "name":"Bo"}]}
It should look like: { "TABLE1": [{ "id": "1", "user": "Larry" }, { "id": "2", "user": "Mo" }, { "id": "4", "user": "Curly" }, { "id": "5", "user": "Shemp" }], "TABLE2": [{ "id": "1", "name": "Ticky" }, { "id": "2", "name": "Tky" }, { "id": "4", "name": "Tem" }, { "id": "5", "name": "Bo" }] }
I can parse TABLE1 but by:
try {
JSONObject jsonObject = new JSONObject(backup);
JSONArray jsonArray = jsonObject.getJSONArray("TABLE1");
for (int i=0;i<jsonArray.length();i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String theId = jsonObject1.getString("_id");
but TABLE2 can't be found using the same code. Any help would be great in building exporting the tables correctly.
Aucun commentaire:
Enregistrer un commentaire