Home > Back-end >  How to append JSON Object to JSON Array file in Android Internal Storage (Kotlin)
How to append JSON Object to JSON Array file in Android Internal Storage (Kotlin)

Time:11-03

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:

  1. Get the content from the target file, store it in a variable, in your case should be a JSONArray object.

  2. Append your JSONObject to the JSONArray.

  3. Write the new JSONArray to the target file, yes, overwrite it.

  • Related