java - 如何使用 JsonWriter 在 Gson 中写入数据而不覆盖/删除以前存储的数据
问题描述
所以在我运行我的代码之前,这是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 的数据,我该怎么做?
解决方案
您可以读取整个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
}
也可以看看:
推荐阅读
- matlab - Matlab: Is it possible to change image axis labels automatically to fit my data?
- azure-ad-b2c - Resetting user password during registration in WingTipGames
- jquery - KeyUp 功能适用于 Firefox 和 Chrome,但不适用于 Safari
- vb.net - Open new email window in Outlook 2019
- memory-leaks - lua garbage collection experience
- node.js - Not able to receive data to the node server on my computer from the client program running on another system in the same network
- java - Checking if a Stack is an arithmetic series | Java
- html - Change div order on mobile screens for expanding div
- jsf - Facelets Template Client doesnt load template
- r - Plot the values of each column as histogram