Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly parse Reddit API in Android

So I've been trying to parse Reddits r/hot/.json API to get a list view of topic information but I cant seem to get my JSON right. I've looked everywhere and I cant seem to find a good example on how to do this for reddit. Here is what I have so far..

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());
        }

-------Edit Okay to give more details I did a HttpGet Request on "http://www.reddit.com/r/hot/.json?sort=new&count=25" When I run my code as it stands I'm getting the following 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

Which is pointing to the first item in my JSON parsing logic. But it makes no sense because there is indeed all of those items in the children array.

like image 803
feilong Avatar asked Dec 11 '22 04:12

feilong


1 Answers

You have to go one more level deeper since the structure is

result
-- data
---- children
------ data
-------- author
-------- thumbnail
-------- created_utc
-------- score
-------- title

Try something like this

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());
}
like image 182
Okky Avatar answered Dec 21 '22 16:12

Okky