使用UTF-16的Gson反序列化问题

时间:2017-01-12 07:54:37

标签: java json utf-8 gson utf-16

我遇到了这行代码的问题:

try (OutputStreamWriter fileout = new OutputStreamWriter(new FileOutputStream(Paths.get(path.toString(), TAGS_FILE.toString()).toString()), "UTF-16")) {
    fileout.write(gson.toJson(imageList, listType));
    fileout.flush();
    fileout.close();
}

我最初使用的是UTF-8,它工作正常,加载得很好,而且必须更改为UTF-16以保留一些特殊字符。它仍然正确写出文件,与UTF-8完全相同(特殊字符除外),但当它试图将文件加载到另一个会话时,我得到“预期BEGIN_ARRAY但是STRING ......” / p>

有解决方法吗?

另外,如果这有帮助:

private final Type listType = new TypeToken<TreeSet<MyClass>>(){}.getType();
TreeSet<MyClass> imageList;

更新:

private void move(File file, Path destination, boolean autoTag) {
    String fileName = file.getName();
    Matcher numberMatcher = leadingNumbersPattern.matcher(fileName);

    // remove leading numbers 
    while (numberMatcher.find()) {
        fileName = clean(fileName, leadingNumbersPattern);
    }

    Matcher artistMatcher = artistPattern.matcher(fileName);
    Matcher newFileNameMatcher = newFileNamePattern.matcher(fileName);

    if (artistMatcher.find() && newFileNameMatcher.find()) {
        // set artist name
        String artist = artistMatcher.group().substring(0, artistMatcher.group().length() - 1);
        // set new picture name
        String newFileName = newFileNameMatcher.group().substring(1);

        Path newPath = Paths.get(destination.toString(), artist);                       // path to artist folder
        new File(newPath.toString()).mkdirs();                                          // make artist folder
        newPath = Paths.get(destination.toString(), artist, newFileName);               // make path to new file location

        try {
            Files.move(file.toPath(), newPath, StandardCopyOption.REPLACE_EXISTING);    // move file to new location
            MyImage newImage = new MyImage(newPath.toString(), artist, newFileName);

1 个答案:

答案 0 :(得分:0)

更改回UTF-8修复了问题。我不得不重新制作json文件;当我最初将所有内容转换为UTF-8时,我猜泰国人物已经不知何故了。

编辑: 找到了原因!我用来反序列化文件的load()方法没有设置为在FileInputStream上使用UTF-8。添加此项可以完全解决问题。