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

Java 用漂亮的打印格式编写JSON文件,java,json,gson,pretty-print,Java,Json,Gson,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

在以下代码中,我们将对象和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那样写入文件并使结果变得漂亮??
感谢allot

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

如何查看文件?记事本因剥去新行而臭名昭著。当你使用记事本++(甚至写字板)这样的编辑器时,你看到换行符被剥离了吗?是的,使用记事本++时,换行符没有剥离,JSON格式非常好。谢谢