简体   繁体   中英

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

For example JSON objects contain strings like 쏘리 but after saving it to a file I see ????

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

How can I fix it? Can I set UTF-8 charset in this code somewhere?

You can try:

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

So do not create FileWriter but OutputStreamWriter that allows you to set the encoding to FileOutputStream .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM