【问题标题】:Gson - Why does my loop mess up my json file?Gson - 为什么我的循环弄乱了我的 json 文件?
【发布时间】: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


    【解决方案1】:

    这里有两个错误:

    • 您问题的实际原因:在循环的最后一次执行中,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);
    

    【讨论】:

      猜你喜欢
      • 2013-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-31
      • 2015-12-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多