【问题标题】:Writing JSON file with pretty print用漂亮的打印编写 JSON 文件
【发布时间】:2016-02-20 12:13:42
【问题描述】:

在以下代码中,我们将对象和 JSON 类型的数组写入文本文件:

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException {


    JSONObject obj = new JSONObject();
    obj.put("Name", "crunchify.com");
    obj.put("Author", "App Shah");

    JSONArray company = new JSONArray();
    company.add("Compnay: eBay");
    company.add("Compnay: Paypal");
    company.add("Compnay: Google");
    obj.put("Company List", company);

    // try-with-resources statement based on post comment below :)
    try (FileWriter file = new FileWriter("file.txt")) {


                    Gson gson = new GsonBuilder().setPrettyPrinting().create();
                    JsonParser jp = new JsonParser();
                    JsonElement je = jp.parse(obj.toJSONString());
                    String prettyJsonString = gson.toJson(je);
                    System.out.println(prettyJsonString);                  

                    file.write(prettyJsonString);
        System.out.println("Successfully Copied JSON Object to File...");
        System.out.println("\nJSON Object: " + obj);

                    file.flush();
                    file.close();
    }


}

}

在下面的代码中,我们漂亮地打印 JSONtostring:

                    Gson gson = new GsonBuilder().setPrettyPrinting().create();
                    JsonParser jp = new JsonParser();
                    JsonElement je = jp.parse(obj.toJSONString());
                    String prettyJsonString = gson.toJson(je);
                    System.out.println(prettyJsonString);                  

prettyJsonString 的打印结果是:

{
      "Name": "crunchify.com",
      "Author": "App Shah",
       "Company List": [
      "Compnay: eBay",
       "Compnay: Paypal",
       "Compnay: Google"
    ]
    }

但是当我们将 prettyJsonString 写入文件时,结果是线性的,看起来不像上面的结果。

file.write(prettyJsonString);

{  "Name": "crunchify.com",  "Author": "App Shah",  "Company List": [    "Compnay: eBay",    "Compnay: Paypal",    "Compnay: Google"  ]}

我们如何写入文件并使结果像上面 prettyJsonString 的 System.out.prinln 一样漂亮漂亮? 感谢分配

【问题讨论】:

  • 您如何查看文件?记事本因剥离新行而臭名昭著。当您使用 Notepad++(甚至是写字板)之类的编辑器时,您看到换行符被删除了吗?
  • 是的,使用记事本++ 不会删除换行符,并且 JSON 格式很漂亮。谢谢

标签: java json gson pretty-print


【解决方案1】:

正如 Nivas 在 cmets 中所说,某些程序会去除换行符,因此查看这些程序(例如记事本)中的输出可能会使它们看起来“丑陋”。确保您在正确显示换行符的程序中查看它们,例如 Notepad++。

【讨论】:

    猜你喜欢
    • 2014-05-19
    • 2012-10-08
    • 2021-01-31
    • 2014-05-12
    • 2013-06-21
    • 2011-08-28
    相关资源
    最近更新 更多