Android2.3解析json出錯

在android2.3上json出現此問題,提示錯誤「JSONException: Value of type java.lang.String cannot be converted to JSONObject」,而4.0上沒問題。 html

部分錯誤log以下: java

  
1 12 - 18 20 : 23 : 27.389 : W / System.err( 12927 ): org.json.JSONException: Value  of type java.lang.String cannot be converted to JSONObject 2 12 - 18 20 : 23 : 27.389 : W / System.err( 12927 ): at org.json.JSON.typeMismatch(JSON.java: 107 ) 3 12 - 18 20 : 23 : 27.389 : W / System.err( 12927 ): at org.json.JSONObject. < init > (JSONObject.java: 158 ) 4 12 - 18 20 : 23 : 27.389 : W / System.err( 12927 ): at org.json.JSONObject. < init > (JSONObject.java: 171 )

 

緣由是服務器返回的數據UTF-8帶有BOM頭,含有BOM頭的數據會多出來三個字節 efbbbf。 android

這樣在解析json的時候就會有問題,android4.0對此已經作了處理,因此沒有報錯。 json

  
1 // android 2.3 2 public JSONTokener(String in) { 3 this .in = in; 4 } 5 6 // android 4.0 7 public JSONTokener(String in) { 8 // consume an optional byte order mark (BOM) if it exists 9 if (in != null && in.startsWith( " \ufeff " )) { 10 in = in.substring( 1 ); 11 } 12 this .in = in; 13 }

參考資料: 服務器

JSONException: Value of type java.lang.String cannot be converted to JSONObject  http://hi.baidu.com/wuuubo/item/761f10134f771ef087ad4e93

UTF-8文件的BOM頭的來由及去除方法

Android 因爲BOM頭致使的Json解析出錯 http://blog.sina.com.cn/s/blog_783ede0301016zdb.html
相關文章
相關標籤/搜索