我目前正在尝试将Twitter Feed添加到我的应用中,目前一切正常,除非我尝试从JSON返回图像url字段。
这是我解析JSON的代码:
public ArrayList<Tweet> getTweets() {
String searchUrl =
"http://twitter.com/statuses/user_timeline/vogella.json";
ArrayList<Tweet> tweets =
new ArrayList<Tweet>();
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(searchUrl);
ResponseHandler<String> responseHandler =
new BasicResponseHandler();
String responseBody = null;
try {
responseBody = client.execute(get, responseHandler);
} catch(Exception ex) {
ex.printStackTrace();
}
JSONObject jsonObject = null;
Log.e("", "responseBody = " + responseBody);
JSONArray arr = null;
try {
arr = new JSONArray(responseBody);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
for (int i = 0; i < arr.length(); i++) {
try {
jsonObject = arr.getJSONObject(i);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Tweet tweet = null;
try {
tweet = new Tweet(
jsonObject.getString("profile_image_url"),
jsonObject.getString("text"),
jsonObject.getString("created_at")
);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tweets.add(tweet);
}
return tweets;
}
这是我得到的错误:
02-14 00:19:18.672: W/System.err(809): org.json.JSONException:JSONObject["profile_image_url"] not found.
尽管存在“profile_image_url” - 点击链接查看JSON - LINK。 Feed中的其他内容似乎都是可检索的,为什么我无法获取图片网址?
答案 0 :(得分:1)
原因如下:
[
{
"user":{
"profile_image_url":"http:\/\/a3.twimg.com\/profile_images\/1249241027 \/LarsVogel10_normal.png",
},
"created_at":"Mon Feb 13 22:34:09 +0000 2012",
"text":"Fun evening at speaker dinner at #jfokus."
},
{
..
...
profile_image_url位于“user”下,而“text”和“created_at”位于
之上答案 1 :(得分:1)
您的jsonObject
变量是指您的回复的顶级数组元素,其中包含in_reply_to_status_id
,geo
等元素。profile_image_url
属性不是属性在该顶级数组元素中,而是user
属性的子元素。
[
{
"in_reply_to_status_id":null,
"in_reply_to_user_id_str":null,
...
"geo":null,
"user":
{
"profile_background_image_url":"http:\/\/a3.twimg.com\/profile_background_images\/112136794\/twilk_background_4c1620bca9ed3.jpg",
...
}
},
...
]
要访问profile_background_image_url
,您必须执行大致如下操作:
JSONObject userObject = jsonObject.getJSONObject ("user");
String url = userObject.getString("profile_image_url");
答案 2 :(得分:1)
我 PRETTY 确保要执行此操作,您必须从具有“profile_image_url”变量的URL中读取JSON。 twitter.com/statuses/
网址没有我认为的变量。 This显示'profile_image_url'位于/profile_images/
。只是让您知道将URL更改为可能能够找到它。 :P