簡體   English   中英

無法將Json漂亮地打印到文本文件

[英]Unable to pretty print Json to text file

如您所見,我需要在文本文件中漂亮地打印JSON對象,但是我現在只能做的是漂亮地將JSON對象打印為輸出。 如果我嘗試將其打印到文本文件中,將不會很漂亮,而只是一個默認的JSON行。

你能看看這個嗎?

package com.crunchify.tutorials;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class CrunchifyJSONFileWrite {
    @SuppressWarnings("unchecked")

    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);

        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);

        try (FileWriter file = new FileWriter("D:/Users/12056/Desktop/pluginnetbeans/jasontestfile.txt")) {
            file.write(prettyJsonString);
            System.out.println("Successfully Copied JSON Object to File...");
            System.out.println("\nJSON Object: " + obj);
        }
    }
}

您的代碼很好。 它可能是您如何查看文件。 用GEdit或Notepad ++之類的文件打開它。

暫無
暫無

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

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