使用漂亮的打印格式编写JSON文件

6
在以下代码中,我们将类型为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();
    }


}

在下面的代码中,我们将JSON格式化输出为字符串:
                    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一样漂亮?谢谢。

http://www.mkyong.com/java/how-to-enable-pretty-print-json-output-gson/ - OneCricketeer
8
你是如何查看这个文件的?记事本因为会去除换行符而臭名昭著。如果你使用像Notepad++(或者甚至是WordPad)这样的编辑器,你会发现换行符被去掉了吗? - Nivas
是的,在notepad++中,换行符不会被去除且JSON格式会很漂亮。谢谢。 - Zimbabaluba
1个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接