我收到來自服務器的響應,並使用Gson將其反序列化爲相應的對象。從服務器反序列化錯誤響應時的NPE
問題是,有時我得到一個錯誤響應(這是當然不是我期望的對象的類型),並導致NullPointerException。 我該如何處理這種情況?
我的代碼是:
Response pollsResponse = okHttpClient.newCall(pollsRequest).execute();
String pollsResponseString = pollsResponse.body().string();
// Gson Type for List of Poll.class oObjects
Type listType = new TypeToken<ArrayList<Poll>>() { }.getType();
pollsList = gson.fromJson(pollsResponseString, listType);
當有一個錯誤的代碼最後一行給NPE。我要如何檢查項目是不是ArrayList<Poll>
類型,所以我不會反序列化它?
編輯:我不明白爲什麼我的問題是相似的鏈接?我知道什麼是NPE。我不知道如何處理我不希望從網絡電話導致NPE的結果。糾正我,如果我錯了。
可能重複[什麼是NullPointerException,以及如何解決它?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-doi-i-fix -it) – 2016-06-08 13:54:09