我對Android開發比較陌生,正在編寫我的第一個基於REST的應用程序。我選擇使用Android Asynchronous HTTP Client使事情變得更簡單。我目前只是通過該鏈接的主要「推薦用法」部分,本質上只是創建一個基本的靜態HTTP客戶端。我遵循給定的代碼,但改變它來引用不同的API。這裏是有問題的代碼:類型不匹配:無法從Object轉換爲JSONObject
public void getFactualResults() throws JSONException {
FactualRestClient.get("q=Coffee,Los Angeles", null, new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONArray venues) {
// Pull out the first restaurant from the returned search results
JSONObject firstVenue = venues.get(0);
String venueName = firstVenue.getString("name");
// Do something with the response
System.out.println(venueName);
}
});
}
的String venueName = firstVenue.getString("name");
線是目前在Eclipse中拋出一個錯誤:「類型不匹配:不能從對象轉換爲JSONObject的」。爲什麼會發生此錯誤?我搜索了其他線程,導致我嘗試使用getJSONObject(0)
而不是get(0)
,但這導致了進一步的錯誤,Eclipse提示使用try/catch。我沒有改變教程中的任何代碼,除了變量名和URL。任何想法/提示/建議?
非常感謝。
編輯:
這裏是的onSuccess方法,修改爲包括try/catch塊建議。 Eclipse現在顯示firstVenue的「局部變量可能未初始化」:venueName = firstVenue.getString("name");
和場所名稱:System.out.println(venueName);
即使在JSONObject firstVenue;
之後直接初始化String venueName;
,我仍然得到相同的錯誤。任何幫助解決這些將不勝感激!
public void onSuccess(JSONArray venues) {
// Pull out the first restaurant from the returned search results
JSONObject firstVenue;
try {
firstVenue = venues.getJSONObject(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String venueName;
try {
venueName = firstVenue.getString("name");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Do something with the response
System.out.println(venueName);
}
請問您可以粘貼您通過獲取請求檢索的場地價值嗎? – 2013-03-13 05:48:31
使用GSON從谷歌,因爲它很容易,快速,重量輕,並採取了所有的痛苦,這離開https://code.google.com/p/google-gson/ – 2013-06-17 22:05:36