我是 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”: [{ “编号”:“1”, “用户”:“拉里” }, { “编号”:“2”, “用户”:“莫” }, { “编号”:“4”, “用户”:“ curl ” }, { “编号”:“5”, “用户”:“羊” }], “表 2”:[{ “编号”:“1”, “名称”:“滴滴” }, { “编号”:“2”, “名字”:“Tky” }, { “编号”:“4”, “名称”:“腾” }, { “编号”:“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。任何帮助都有助于正确构建导出表。
最佳答案
从代码中间删除 ps.append(mObject.toString());
,并将最后两行更改为:
mObject.put("TABLE2", tab2Array);
ps.append(mObject.toString());
关于Android sqlite 表到 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34914687/