我对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