将JSON文件写为UTF-8编码

时间:2015-03-16 16:24:01

标签: java json utf-8

我正在编写一个将一些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对象的arraylist,由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£€]*$"
      }
}

但是,它显示在记事本++中。在氧气中,它显示如下:

"pattern_match" : {
        "$record.ApplicationData.SiteVisit.VisitContactDetails.ContactOther.PersonName.PersonGivenName" : "^[\\u0000-\\u005F\\u0061-\\u007B\\u007d-\\u007f£€]*$"
 }

1 个答案:

答案 0 :(得分:2)

构建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可以为您管理OutputStreamWriterFileOutputStream个对象:

Writer out = new PrintWriter(fileDir, "UTF-8");

或者:

Writer out = new PrintWriter("test.json", "UTF-8");

最后,为什么要使用BufferedWriter创建Files.newBufferedWriter()只是为了忽略它并手动创建辅助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));
}