我正在编写一种将一些 JSON 写入文件的方法,该方法运行良好。然而,尽管我已将输出设置为 UTF-8,Oxygen无法读取英镑和欧元符号。
Java代码:
Path logFile = Paths.get(this.output_folder + "/" + file.getName().split("\\.")[0] + ".json");
try (BufferedWriter writer = Files.newBufferedWriter(logFile, StandardCharsets.UTF_8)) {
File fileDir = new File("test.json");
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileDir), "UTF8"));
ObjectMapper mapper = new ObjectMapper();
writer.write(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(all_questions));
}
“all_questions”是 Question 对象的数组列表,由 ObjectMapper 打印为格式化的 JSON 片段。
一些带有井号的示例 JSON 如下所示:
{
"name" : "RegExRule",
"field" : "Q039_4",
"rules" : [ ],
"fileName" : "s1rules_england_en.xml",
"error" : null,
"pattern_match" : {
"$record.ApplicationData.SiteVisit.VisitContactDetails.ContactOther.PersonName.PersonGivenName" : "^[\\u0000-\\u005F\\u0061-\\u007B\\u007d-\\u007f£€]*$"
}
}
但是,这是在 Notepad++ 中显示的。在Oxygen中,显示如下:
"pattern_match" : {
"$record.ApplicationData.SiteVisit.VisitContactDetails.ContactOther.PersonName.PersonGivenName" : "^[\\u0000-\\u005F\\u0061-\\u007B\\u007d-\\u007f£€]*$"
}
最佳答案
构造OutputStreamWriter
对象时,需要使用"UTF-8"
作为字符集名称,而不是"UTF8"
:
new OutputStreamWriter(..., "UTF-8")
或者,使用 StandardCharsets.UTF_8
代替:
new OutputStreamWriter(..., StandardCharsets.UTF_8)
Java 通常不支持读/写 BOM,因此如果您希望 JSON 文件具有 UTF-8 BOM,则必须手动编写一个:
Writer out = ...;
out.write("\uFEFF");
out.write(... json content here ...);
仅供引用,PrintWriter
可以为您管理OutputStreamWriter
和FileOutputStream
对象:
Writer out = new PrintWriter(fileDir, "UTF-8");
或者:
Writer out = new PrintWriter("test.json", "UTF-8");
最后,为什么您使用 Files.newBufferedWriter()
创建一个 BufferedWriter
却忽略它并手动创建一个辅助 BufferedWriter
?为什么不直接使用您已有的 BufferedWriter
:
Path logFile = Paths.get(this.output_folder + "/" + file.getName().split("\\.")[0] + ".json");
try (BufferedWriter writer = Files.newBufferedWriter(logFile, StandardCharsets.UTF_8)) {
writer.write("\uFEFF");
ObjectMapper mapper = new ObjectMapper();
writer.write(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(all_questions));
}
关于java - 将 JSON 文件写入 UTF-8 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29081921/