我编写了一段代码,从网站获取 JSON 文本并对其进行格式化,以便更易于阅读。我的代码问题是:
public static void gsonFile(){
try {
re = new BufferedReader(new FileReader(dateiname));
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
String uglyJSONString ="";
uglyJSONString = re.readLine();
JsonElement je = jp.parse(uglyJSONString);
String prettyJsonString = gson.toJson(je);
System.out.println(prettyJsonString);
wr = new BufferedWriter(new FileWriter(dateiname));
wr.write(prettyJsonString);
wr.close();
re.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
它正确地将其打印到控制台:http://imgur.com/B8MTlYW.png
但是在我的txt文件中它看起来像这样:http://imgur.com/N8iN7dv.png
我该怎么做才能将其正确打印到文件中? (用新行分隔)
最佳答案
Gson 使用 \n
作为行分隔符(如 newline
方法 here 所示)。
由于记事本无法理解\n
,您可以使用其他文件编辑器打开结果文件(写字板、Notepad++、Atom、Sublime Text)等)或在写入之前将 \n
替换为 \r\n
:
prettyJsonString = prettyJsonString.replace("\n", "\r\n");
关于java - BufferedWriter 无法正确写入 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39333219/