Gson-为什么我的循环会弄乱我的json文件



这是我的"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"
}
}
}

我不确定为什么会发生这种情况,我已经尝试过多次修复它。

这里有两个错误:

  • 问题的实际原因:在循环的最后一次执行时,调用value.addProperty,然后if下降,执行else块,从而导致结果。只需将第二个if更改为else if或在value.addProperty之后添加一个中断即可。

  • 在修复之后,这仍然不能很好地工作,因为您正在覆盖value变量(在方法1中没有这样做(。尝试第一个修复程序,看看会发生什么,你的文件中会有"双json"。修复很简单:只写原始值,而不是操作后的值。

JsonObject value = gson.fromJson(reader, JsonObject.class);
JsonObject originalValue = value;
...
gson.toJson(originalValue, writer);

最新更新