【发布时间】:2013-03-13 05:15:43
【问题描述】:
我对 Android 开发比较陌生,正在编写我的第一个基于 REST 的应用程序。我选择使用Android Asynchronous HTTP Client 让事情变得更容易一些。我目前正在浏览该链接上的主要“推荐用法”部分,基本上只是创建一个基本的静态 HTTP 客户端。我正在遵循给出的代码,但将其更改为引用不同的 API。这是有问题的代码:
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 中引发错误:“类型不匹配:无法从 Object 转换为 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);
}
【问题讨论】:
-
能否粘贴您通过获取请求检索到的场所值?
-
使用来自 google 的 GSON,因为它简单、快速、重量轻,可以消除所有痛苦code.google.com/p/google-gson