生成json文件的同时保留原json格式,拥有良好的格式(如缩进等),提供友善阅读支持。
pom.xml依赖增加:
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.7</version>
</dependency>public static boolean generateJsonFile(JSONObject jsonObj, String filePath) {
    // 标记文件生成是否成功
    boolean flag = true;
    // 生成json格式文件
    try {
      // 保证创建一个新文件
      File file = new File(filePath);
      if (file.exists()) { // 如果已存在,删除旧文件
        file.delete();
      }
      file.createNewFile();
      FileWriter fileWriter = new FileWriter(filePath);
      Gson gson = new GsonBuilder().setPrettyPrinting().create();
      String jsonOutput = gson.toJson(jsonObj);
      fileWriter.write(jsonOutput);
      fileWriter.flush();
    } catch (Exception e) {
      flag = false;
      e.printStackTrace();
    }
    return flag;
  }生成后的效果:




















