【发布时间】:2020-09-01 21:25:41
【问题描述】:
这是我运行代码之前的“example.json”:
{
"example1": {
"example2": {
"example3": 30
}
}
}
当我运行这段代码时:
JsonManager.writeString("example", "example1", "example2", "example7", "70");
这个函数:
public static void writeString(String fileName, String ... objects) throws IOException {
Path jsonFile = Paths.get("src/" + fileName + ".json");
try (BufferedReader reader = Files.newBufferedReader(jsonFile);
BufferedWriter writer = Files.newBufferedWriter(jsonFile, StandardOpenOption.WRITE)) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonObject value = gson.fromJson(reader, JsonObject.class);
// Method 1:
value.getAsJsonObject(objects[0]).getAsJsonObject(objects[1]).addProperty(objects[2], objects[3]); //
// Method 2:
String property = null;
int i = 0;
for (String s : objects) {
i++;
if (i == objects.length) {
value.addProperty(property, s);
}
if (i == objects.length - 1) {
property = s;
} else {
value = value.getAsJsonObject(s);
}
} //
gson.toJson(value, writer);
}
}
现在,上述函数中的方法 1 可以像故意对“example.json”一样:
{
"example1": {
"example2": {
"example3": 30,
"example7": "70"
}
}
}
方法 2 对“example.json”执行此操作:
null"example1": {
"example2": {
"example3": 30,
"example7": "70"
}
}
}
我不确定为什么会发生这种情况,我已尝试多次修复它。
【问题讨论】:
标签: java json gson writetofile