Android sqlite表到json文件
我是json新手。我试图将两个Sqlite表放入一个json文本文件中。我能够获取每个表并发送到文本文件,但如果我尝试从文件中读取字符串,则结果无效 代码如下:Android sqlite表到json文件,android,json,sqlite,Android,Json,Sqlite,我是json新手。我试图将两个Sqlite表放入一个json文本文件中。我能够获取每个表并发送到文本文件,但如果我尝试从文件中读取字符串,则结果无效 代码如下: File f = new File(Constants.DEFAULT_BACKUP_FILE_PATH); FileOutputStream fos = new FileOutputStream(f,true); PrintStream ps = new PrintStream(fos); Strin
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());
我的文本文件如下所示(请注意,两者之间没有逗号):
{“表1”:[{“id”:“1”,“用户”:“Larry”},{“id”:“2”,“用户”:“Mo”},{“id”:“4”,“用户”:“Curly”},{“id”:“5”,“用户”:“Shemp”}]}
{“表2”:[{“id”:“1”,“name”:“Ticky”},{“id”:“2”,“name”:“Tky”},{“id”:“4”,“name”:“Tem”},{“id”:“5”,“name”:“Bo”}]}
它应该是这样的:
{
“表1”:[{
“id”:“1”,
“用户”:“拉里”
}, {
“id”:“2”,
“用户”:“Mo”
}, {
“id”:“4”,
“用户”:“卷发”
}, {
“id”:“5”,
“用户”:“Shemp”
}],
“表2”:[{
“id”:“1”,
“名称”:“Ticky”
}, {
“id”:“2”,
“名称”:“Tky”
}, {
“id”:“4”,
“名称”:“Tem”
}, {
“id”:“5”,
“姓名”:“博”
}]
}
我可以解析表1,但方法是:
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");
试试看{
JSONObject JSONObject=新的JSONObject(备份);
JSONArray JSONArray=jsonObject.getJSONArray(“表1”);
对于(int i=0;i从代码中间删除ps.append(mObject.toString());
,并将最后两行更改为:
mObject.put("TABLE2", tab2Array);
ps.append(mObject.toString());
太好了!非常感谢!!!感谢您的快速响应。我在添加数组之前关闭了主对象。