我正在尝试将JSON对象写入包含JSONArray的文件。在将此对象写入TXT文件之前,我检查每个结构在控制台中打印它。例如,我得到了这个:
{"splittedHostEnteredString":["cześć.","w"],"foreignLanguage":"cześć","historyToWord":"cześć. w","mainLanguage":"jak","country":0}
在列表中,我有例如上面的10个对象,每个对象都正确打印。问题是当我尝试编写将所有对象都作为字符串的ArrayList时。文件也写入,但在它之后,还有一些额外的字符 - 所有结构中的“\”。我使用GSON库将对象转换为字符串。以下是保存文件后的输出:
{"names":["{\"splittedHostEnteredString\":[\"cześć.\",\"każdym\"],\"foreignLanguage\":\"jak\",\"historyToWord\":\"cześć. w każdym razie\",\"mainLanguage\":\"z\",\"country\":0}","{\"splittedHostEnteredString\":[\"cześć.\",\"w\"],\"foreignLanguage\":\"cześć\",\"historyToWord\":\"cześć. w\",\"mainLanguage\":\"jak\",\"country\":0}"]}
这是我的代码:
public void saveListOfExistingObjectsInApplicationToOneFileJson()
{
String filename = "configuration.txt";
File myFile = new File(Environment.getExternalStorageDirectory(), filename);
try {
myFile.createNewFile();
JSONObject obj = new JSONObject();
try {
JSONArray array = new JSONArray();
for(int i = 0; i < listOfSavedFiles.size(); i++)
{
array.put(listOfSavedFiles.get(i));
}
obj.put("names", array);
System.out.println(obj.toString());
String tmpStringToWrite = obj.toString();
FileOutputStream stream = new FileOutputStream(myFile);
try {
stream.write(tmpStringToWrite.getBytes());
} finally {
stream.close();
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}