我需要在文本文件中打印一个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);
}
}
}
答案 0 :(得分:1)
你的代码很好。它可能是你查看文件的方式。用像GEdit或Notepad ++这样的东西打开它。