【问题标题】:Saving a JSON String in Java to a file将 Java 中的 JSON 字符串保存到文件中
【发布时间】:2013-06-25 03:18:44
【问题描述】:

所以我使用 GSON 将我的对象转换为字符串,这对以下代码非常有用: 然而,我现在想做的是将字符串保存到一个文件(如 .txt)中,然后在另一台计算机上打开该文本文件并加载 JSON 对象。

Gson gson = new Gson();
String myObjectJson = gson.toJson(digitsSVM);
System.out.println(myObjectJson); // <--- this is working

我的问题是如何将此字符串保存到标准文件中,然后在将其转换回我的对象​​之前打开它?

MyObj obj = gson.fromJson(myObjectJson, MyObj.class); // converts it back to my object

【问题讨论】:

    标签: java string io


    【解决方案1】:

    文件可以被视为流,所以只需使用 JsonReader 和 JsonWriter。可以在here 和文档here 中找到一个示例。

    【讨论】:

      【解决方案2】:

      首先阅读Basic I/O

      但基本过程将遵循...

      // To write...
      BufferedWriter bw = null;
      try {
          bw = new BufferedWriter(new FileWriter(new File("MyJson.txt")));
          bw.write(myObjectJson);
      } finally {
          try {
              bw.close();
          } catch (Exception e) {
          }
      }
      
      // To Read
      BufferedReader br = null;
      try {
          br = new BufferedReader(new FileWriter(new File("MyJson.txt")));
          myObjectJson = br.readLine();
      } finally {
          try {
              br.close();
          } catch (Exception e) {
          }
      }
      

      注意,这两个操作会抛出一个IOException,我没有发现,因为你需要根据你的要求来处理它

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-11
        • 1970-01-01
        • 2012-02-03
        • 2010-11-06
        • 1970-01-01
        相关资源
        最近更新 更多