2015-03-03 146 views
0

我有一個簡單的代碼那樣:GSON庫時解析字符串包含特殊字符ü

JsonParser parser = new JsonParser(); 
JsonElement element = parser.parse("{\"description\":\"c:\\userDescription.txt\"}"); 
JsonObject attributes = element.getAsJsonObject(); 
System.out.println(attributes); 

我期待outout是:

{"description":"c:\userDescription.txt"} 

,但實際上我有exeption:

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: For input string: "serD" 

你能幫我嗎,輸入是什麼應該得到期望的輸出:

{"description":"c:\userDescription.txt"} 

回答

0

下面的Java字符串是一個字符長,\字符:

String s = "\\"; 

Java一樣,JSON使用\作爲轉義字符。因此,對於JSON,您需要爲Java 轉義。試試這個:

JsonElement element = parser.parse("{\"description\":\"c:\\\\userDescription.txt\"}"); 
+0

如果我這樣做,輸出爲:{ 「說明」: 「C:\\ userDescription.txt」} 但我想到的是{ 「說明」:「C:\ userDescription.txt 「} – 2015-03-03 05:34:20

+0

您的期望是無效的JSON。 \角色必須逃脫。 – 2015-03-09 03:50:15

+0

是的,謝謝。我通過你的建議解決了這個問題。 – 2015-03-24 06:57:36