【发布时间】:2016-01-21 03:03:09
【问题描述】:
我是 json 新手。我正在尝试将两个 Sqlite 表放入一个 json 文本文件中。我能够获取每个表并发送到文本文件,但如果我尝试从文件中读取字符串,我的结果将无效。
代码如下:
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());
我的文本文件如下所示(注意两者之间没有逗号):
{"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"}]}
它应该看起来像: { “表格1”: [{ “id”:“1”, “用户”:“拉里” }, { “id”:“2”, “用户”:“莫” }, { “id”:“4”, “用户”:“卷曲” }, { “id”:“5”, “用户”:“Shemp” }], “表2”:[{ “id”:“1”, “名称”:“Ticky” }, { “id”:“2”, “名称”:“Tky” }, { “id”:“4”, “名称”:“项目” }, { “id”:“5”, “姓名”:“博” }] }
我可以通过以下方式解析 TABLE1:
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");
但无法使用相同的代码找到 TABLE2。任何有助于正确构建导出表的帮助。
【问题讨论】: