我目前有一个问题,我在内部存储中保留了一个json文件,我希望将一个新对象附加到该文件中。
这就是我制作文件的方式:
val fOut = openFileOutput("notes.txt", MODE_PRIVATE)
val str = "[]"
fOut.write(str.toByteArray())
fOut.close()
这导致文件看起来像这样:
[]
到目前为止还不错,现在我需要在json文件中添加一个新对象:
val fileOutputSream = openFileOutput("jsonfile.json", MODE_APPEND)
fileOutputSream.write(obj.toString().toByteArray())
fileOutputSream.close()
但最终总是这样:
[]{"item1": "value1", "item2": "value2", "item3": "value3"}
不是这样的:
[
{"item1": "value1", "item2": "value2", "item3": "value3"}
]
使用Java代码编写json;
JSONObject jsonObject;
try {
Writer output = null;
File file = new File(Path +"/jsonfile.json");
output = new BufferedWriter(new FileWriter(file));
output.write(jsonObject.toString());
output.close();
Toast.makeText(getApplicationContext(), "Composition saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
我认为您需要:
-
从目标文件中获取内容,将其存储在变量中,在您的情况下应该是
JSONArray
对象。 -
将您的
JSONObject
附加到JSONArray
。 -
将新的
JSONArray
写入目标文件,是的,覆盖它。