【问题标题】:How to append JSON Object to JSON Array file in Android Internal Storage (Kotlin)如何将 JSON 对象附加到 Android 内部存储 (Kotlin) 中的 JSON 数组文件
【发布时间】:2022-11-02 20:15:12
【问题描述】:

我目前有一个问题,我将一个 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"}
]

【问题讨论】:

    标签: android


    【解决方案1】:

    尝试使用 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();
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-23
      • 2023-01-12
      • 2014-06-26
      • 2017-03-26
      相关资源
      最近更新 更多