因此,我一直在尝试解析Reddits r / hot / .json API以获取主题信息的列表视图,但是我似乎无法正确获取JSON。我到处都看过了,我似乎找不到如何在Reddit上做一个很好的例子。这是我到目前为止所拥有的。
JSONObject response = new JSONObject(result);
JSONObject data = response.getJSONObject("data");
JSONArray hotTopics = data.getJSONArray("children");
for(int i=0; i<hotTopics.length(); i++) {
JSONObject topic = hotTopics.getJSONObject(i);
String author = topic.getString("author");
String imageUrl = topic.getString("thumbnail");
String postTime = topic.getString("created_utc");
String rScore = topic.getString("score");
String title = topic.getString("title");
topicdata.add(new ListData(title, author, imageUrl, postTime, rScore));
Log.v(DEBUG_TAG,topicdata.toString());
}
- - - -编辑
可以提供更多详细信息,我对“http://www.reddit.com/r/hot/.json?sort=new&count=25”执行了HttpGet请求
当我按原样运行代码时,我得到以下JSONException
07-06 22:23:11.628 2580-2580/com.google.android.gms.redditviewr.app W/System.err﹕ org.json.JSONException: No value for author07-06 22:23:11.632 2580-2580/com.google.android.gms.redditviewr.app W/System.err﹕ at org.json.JSONObject.get(JSONObject.java:354)07-06 22:23:11.632 2580-2580/com.google.android.gms.redditviewr.app W/System.err﹕ at org.json.JSONObject.getString(JSONObject.java:514)07-06 22:23:11.636 2580-2580/com.google.android.gms.redditviewr.app W/System.err﹕ at Tasks.RedditApiTask.onPostExecute(RedditApiTask.java:78)07-06 22:23:11.636 2580-2580/com.google.android.gms.redditviewr.app W/System.err﹕ at Tasks.RedditApiTask.onPostExecute(RedditApiTask.java:22)07
指向我的JSON解析逻辑中的第一项。但这是没有意义的,因为在子数组中确实存在所有这些项。
最佳答案
因为结构是
result
-- data
---- children
------ data
-------- author
-------- thumbnail
-------- created_utc
-------- score
-------- title
试试这个
for (int i = 0; i < hotTopics.length(); i++) {
JSONObject topic = hotTopics.getJSONObject(i).getJSONObject("data");
String author = topic.getString("author");
String imageUrl = topic.getString("thumbnail");
String postTime = topic.getString("created_utc");
String rScore = topic.getString("score");
String title = topic.getString("title");
topicdata.add(new ListData(title, author, imageUrl, postTime, rScore));
Log.v(DEBUG_TAG, topicdata.toString());
}