簡體   English   中英

用漂亮的字體編寫 JSON 文件

[英]Writing JSON file with pretty print

在以下代碼中,我們將對象和 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 一樣漂亮? 感謝分配

正如 Nivas 在評論中所說,一些程序會去除換行符,因此查看這些程序(例如記事本)中的輸出可能會使它們看起來“丑陋”。 確保您在正確顯示換行符的程序中查看它們,例如 Notepad++。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM