编写清晰的JSON文件

问题描述 投票:5回答:1

在下面的代码中,我们将对象和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一样??谢谢分配

java json gson pretty-print
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.