2017-01-12 26 views
0

我有一个问题,与这行代码: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完全相同(除了特殊字符in-tact),但是当它试图将文件加载到另一个会话中时,我得到“期望的BEGIN_ARRAY但是STRING ...”

有没有办法解决这个问题?

而且,如果这能帮助:

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

UPDATE:

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); 
+2

UTF-8应该表示Unicode标准中的所有*字符。也许最好是解决原来的问题,而不是一个新问题。 – RealSkeptic

+0

那么@RealSkeptic我遇到了泰文字符......它保存为...不是泰语字符在json文件中。如果你有建议让它正确地写人物,我会非常高兴。 – Kofu

+1

首先,标准json应该支持'\ uXXXX'格式的任何字符。因此,即使US-ASCII中的JSON也可以包含泰文或任何脚本中的字符。但是可以编辑你的问题并添加一个写入文件的例子类,产生的JSON和你的期望? – RealSkeptic

回答

0

变回UTF-8固定的问题。我不得不重制json文件;我猜想,当我将所有内容最初转换为UTF-8时,泰国汉字都不知怎么溜过了。编号: 找到原因了!我用来反序列化文件的load()方法没有设置为在FileInputStream上使用UTF-8。添加这个问题完全解决了问题。