【问题标题】:Empty json file when using gson使用 gson 时的空 json 文件
【发布时间】:2021-07-05 20:31:35
【问题描述】:

当我运行此代码时,文件被创建,但它是空的,虽然输出看起来不错

import java.io.IOException;

public class JasonTest {
    public static void main(String[] args) throws IOException {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        TestJson tj = new TestJson(13, "kuku");
        gson.toJson(tj, new FileWriter("test.json"));
        System.out.println(gson.toJson(tj));

    }
}

输出:

{
  "num": 13,
  "text": "kuku"
}

Process finished with exit code 0

【问题讨论】:

    标签: java gson


    【解决方案1】:

    this question。您需要关闭FileWriter(如果目前还不能关闭,则刷新)。比如:

    FileWriter fw = new FileWriter("test.json");
    gson.toJson(tj, fw);
    fw.close();
    

    使用 try/resources 或更好:

    // Does auto close
    try(FileWriter fw = new FileWriter("test.json")) {
        gson.toJson(tj, fw);            
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-28
      • 1970-01-01
      • 2012-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多