将 JSON 保存到文件时出现编码问题,如何保存为 UTF-8?

Encoding issues when saving JSON to a file, howto save as UTF-8?

例如 JSON 对象包含类似 쏘리 的字符串,但在将其保存到文件后我看到 ????

try (Writer writer = new FileWriter(file)) {
    Gson gson = new GsonBuilder().create();
    gson.toJson(jsonObject, writer);
}

我该如何解决?我可以在这段代码的某处设置 UTF-8 字符集吗?

你可以试试:

try (Writer writer = new OutputStreamWriter(
                        new FileOutputStream(path),"UTF-8")) {
    Gson gson = new GsonBuilder().create();
    gson.toJson(jsonObject, writer);
}

所以不要创建 FileWriter,而是创建 OutputStreamWriter,这样您就可以将编码设置为 FileOutputStream