【问题标题】:How to write data in Gson using JsonWriter and not override/remove previously stored data如何使用 JsonWriter 在 Gson 中写入数据而不覆盖/删除以前存储的数据
【发布时间】:2020-08-12 13:20:29
【问题描述】:

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

{
  "example1": 5
}

当我执行这段代码时:

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

那么这发生在example.json上:

{"example2":13}

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

【问题讨论】:

    标签: java json gson writing


    【解决方案1】:

    试试 JsonWriter exampleWriter = new JsonWriter(new FileWriter(examplePath, true));

    【讨论】:

      【解决方案2】:

      您可以将整个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
      }
      

      另见:

      【讨论】:

        猜你喜欢
        • 2020-08-20
        • 2012-04-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-14
        • 1970-01-01
        • 2017-09-04
        • 1970-01-01
        相关资源
        最近更新 更多