2014-02-11 102 views
1

在我的GSON測試類中,我有一個類必須被序列化的字符串。GSON - 使用unicode字符

問題是,特殊的Unicode字符如\u06A4轉換爲?。這不是我想要這個工作。

這裏是我的類:

public final class JSONvsBinary { 

    public static final void run() throws Exception { 

     A a1 = new A(); 
     a1.a = "bla, blu., € @ xyz Ø, \u06A4 ►"; 

     GsonBuilder builder = new GsonBuilder(); 
     builder.excludeFieldsWithModifiers(Modifier.TRANSIENT); 
     builder.setPrettyPrinting(); 
     builder.disableHtmlEscaping(); 
     builder.serializeNulls(); 
     builder.serializeSpecialFloatingPointValues(); 
     Gson gson = builder.create(); 

     final String gsonString = gson.toJson(a1, A.class); 
     final byte[] gsonBytes = gsonString.getBytes("UTF8"); 
     System.out.println("GSON:\n" + new String(gsonBytes, "UTF8")); 
     System.out.println("GSON bytes: " + gsonBytes.length); 

    } 

    @SuppressWarnings("unused") 
    private static final class A { 

     public String a; 

    } 

} 

這就是輸出:

GSON: 
{ 
    "a": "bla, blu., € @ xyz Ø, ? ?" 
} 
GSON bytes: 44 

我設置字節編碼成UTF-8,但它不工作...

+1

老實說,這與Gson無關 - 您的終端不能正確顯示這些字符。在我的機器上工作得很好。 –

+0

哦,有趣。我如何顯示這些消息?使用JOptionPanes? – MinecraftShamrock

+1

系統上的默認字符集是什麼?似乎很奇怪它是* not * utf-8。除非...是這個窗口,你正在使用命令行?這是可能解釋它的windows-1252的問題。如果是這樣,是的......或者使用帶有控制檯窗口的IDE。 –

回答

3

一,確保你的編譯器和編輯器是using the same encoding。這在IDE中通常不是問題。

問題可能出在這裏:System.out.println

documentation for PrintStream

PrintStream印刷的所有字符被轉換成使用平臺的默認字符編碼字節。

因此,根據the platform encoding,System.out可能會丟失數據。

最重要的是,設備System.out的渲染引擎正在發送數據,必須支持用於呈現字符數據中每個代碼點的字形。

+0

很高興知道。謝謝。 – MinecraftShamrock