I currently have a problem where I'm keeping a json file in the internal storage, and I wish to append a new object into that file.
This is how I make the file:
val fOut = openFileOutput("notes.txt", MODE_PRIVATE)
val str = "[]"
fOut.write(str.toByteArray())
fOut.close()
Which results in the file looking like this:
[]
So far so good, now I need to append a new object to that json file:
val fileOutputSream = openFileOutput("jsonfile.json", MODE_APPEND)
fileOutputSream.write(obj.toString().toByteArray())
fileOutputSream.close()
But it always ends up looking like this:
[]{"item1": "value1", "item2": "value2", "item3": "value3"}
And not like this:
[
{"item1": "value1", "item2": "value2", "item3": "value3"}
]
CodePudding user response:
Try With The Java Code to Write 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();
}
CodePudding user response:
I think you need to:
Get the content from the target file, store it in a variable, in your case should be a
JSONArray
object.Append your
JSONObject
to theJSONArray
.Write the new
JSONArray
to the target file, yes, overwrite it.