com.google.gson.JsonSyntaxException:com.google.gson.stream.MalformedJsonException:Unterminated objec
最近做專案呼叫介面返回比較複雜的json資料,在解析的時候一直報這樣的錯,sonSyntaxException:com.google.gson.stream.MalformedJsonException:Unterminated objec at line 1 column 423 path .... 把接收的json打印出來也是完整的。
到處查資料搞了好久,偶然機會看到關於編碼問題,原來tomcat預設是ISO-8859-1,讀取的介面資料中文亂碼,修改InputStreamReader編碼格式解決問題。
兩種解決方法:
方法一,設定tomcat字元編碼為utf-8,這種方法缺點很大,要是哪天重灌了tomcat又忘了設定了,那就大大的bug了~所以我直接跳過,
方法二,程式碼中進行編碼轉換,我使用的是BufferedReader,中間加一個InputStreamReader進行編碼轉換,這下總不會亂碼了吧!呵呵,上程式碼:
public SajIot getHttpResponse(String allConfigUrl) {BufferedReader in = null;
StringBuffer result = null;
try {
URI uri = new URI(allConfigUrl);
URL url = uri.toURL();
URLConnection connection = url.openConnection();
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Charset", "utf-8");
connection.connect();
System.out.println("url地址是:"+url.toString());
result = new StringBuffer();
in = new BufferedReader(new InputStreamReader( // 讀取URL的響應
connection.getInputStream(),"utf-8
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
String json=result.toString();
Gson gson = new Gson();
JsonBean jsonBean = gson.fromJson(json, JsonBean.class);
List<UserInfoVos> userInfoVo=jsonBean.getUserInfoVos();
for(int i=0;i<userInfoVo.size();i++){
UserInfoVo infoVo=userInfoVo.get(i).getUserInfoVo();
if(infoVo.getPackageCode()=="prod.10086000002301"){
String packageCode= infoVo.getPackageCode();
String packageName= infoVo.getPackageName();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return sajIot;
}