如何在Android中正确解析Reddit API

fei*_*ong 4 java android json reddit

所以我一直在尝试解析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());
        }
Run Code Online (Sandbox Code Playgroud)

-------编辑可以提供更多详细信息我在" 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 author 07-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解析逻辑中的第一项.但这没有任何意义,因为在children数组中确实存在所有这些项目.

Okk*_*kky 9

自结构以来,你必须更深入一层

result
-- data
---- children
------ data
-------- author
-------- thumbnail
-------- created_utc
-------- score
-------- title
Run Code Online (Sandbox Code Playgroud)

尝试这样的事情

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());
}
Run Code Online (Sandbox Code Playgroud)

  • 到底在哪里找到结构?我不确定是否只是我是新手,但 Reddit 的 api 文档有点难以理解和理解 (2认同)