微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用JsonWriter在Gson中写入数据,而不覆盖/删除先前存储的数据

如何解决如何使用JsonWriter在Gson中写入数据,而不覆盖/删除先前存储的数据

所以在运行代码之前,这是example.json:

fetch_object()

当我执行此代码时:

{
  "example1": 5
}

然后这发生在example.json:

JsonWriter exampleWriter = new JsonWriter(new FileWriter(examplePath));
exampleWriter.beginobject();
exampleWriter.name("example2").value(13);
exampleWriter.endobject();
exampleWriter.close();

我希望example.json包含example1和example2的数据,我该怎么做?

解决方法

尝试 JsonWriter exampleWriter =新的JsonWriter(新的FileWriter(examplePath,true));

,

您可以将整个JSON有效负载读取为JsonObject并添加新属性。之后,您可以将其序列化回JSON

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class GsonApp {

    public static void main(String[] args) throws IOException {
        Path pathToJson = Paths.get("./resource/test.json");

        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        try (BufferedReader reader = Files.newBufferedReader(pathToJson);
             BufferedWriter writer = Files.newBufferedWriter(pathToJson,StandardOpenOption.WRITE)) {
            JsonObject root = gson.fromJson(reader,JsonObject.class);
            root.addProperty("example2",13);
            gson.toJson(root,writer);
        }
    }
}

上面的代码生成:

{
  "example1": 5,"example2": 13
}

另请参阅:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。