有人可以解决JSONException这个问题吗?

时间:2019-12-08 13:20:59

标签: java android json

我得到这个:E/fetchPosts(): org.json.JSONException: End of input at character 0 of

我正试图在subreddit api中输入“ askreddit”并尝试显示在我的应用中。不知道怎么了我确实在清单中使用了cleartexttraffic true,还添加了Internet权限

我的JSON不正确

我正在尝试在“孩子”下

我正在关注以下示例:http://www.whycouch.com/2012/12/how-to-create-android-client-for-reddit.html

PostsHolder.java

package com.jimmytrivedi.jimmytrivedi_reddit;

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class PostsHolder {

    /**
     * We will be fetching JSON data from the API.
     */
    private final String URL_TEMPLATE =
            "http://www.reddit.com/r/SUBREDDIT_NAME/"
                    + ".json"
                    + "?after=AFTER";

    String subreddit;
    String url;
    String after;

    PostsHolder(String sr) {
        subreddit = sr;
        after = "";
        generateURL();
    }

    /**
     * Generates the actual URL from the template based on the
     * subreddit name and the 'after' property.
     */
    private void generateURL() {
        url = URL_TEMPLATE.replace("SUBREDDIT_NAME", subreddit);
        url = url.replace("AFTER", after);
    }

    /**
     * Returns a list of Post objects after fetching data from
     * Reddit using the JSON API.
     *
     * @return
     */
    List<Post> fetchPosts() {
        String raw = RemoteData.readContents(url);
        List<Post> list = new ArrayList<Post>();
        try {
            JSONObject data = new JSONObject(raw)
                    .getJSONObject("data");
            JSONArray children = data.getJSONArray("children");

            //Using this property we can fetch the next set of
            //posts from the same subreddit
            after = data.getString("after");

            for (int i = 0; i < children.length(); i++) {
                JSONObject cur = children.getJSONObject(i)
                        .getJSONObject("data");
                Post p = new Post();
                p.title = cur.optString("title");
                p.url = cur.optString("url");
                p.numComments = cur.optInt("num_comments");
                p.points = cur.optInt("score");
                p.author = cur.optString("author");
                p.subreddit = cur.optString("subreddit");
                p.permalink = cur.optString("permalink");
                p.domain = cur.optString("domain");
                p.id = cur.optString("id");
                if (p.title != null)
                    list.add(p);
            }
        } catch (Exception e) {
            Log.e("fetchPosts()", e.toString());
        }
        return list;
    }

    /**
     * This is to fetch the next set of posts
     * using the 'after' property
     *
     * @return
     */
    List<Post> fetchMorePosts() {
        generateURL();
        return fetchPosts();
    }
}

0 个答案:

没有答案