解析JSON时出错

时间:2013-12-01 04:52:24

标签: java json twitter android-volley

我正在与Volley和org.json合作,在Twitter中从用户时间线中提取JSON。我收到了#34;错误请求"来自我的onErrorResponse。它似乎不是一个URL问题,因为我在LogCat中看到了所需的JSON。这是错误日志:

11-30 22:54:52.273: W/TweetLoader(18610): Error with request
11-30 22:54:52.273: W/System.err(18610): com.android.volley.ParseError: org.json.JSONException: Value [{"contributors":null,"text":"18-propeller copter might be the future of personal air travel, inventors say.\nhttp:\/\/t.co\/TMUtbF80Kp via @CNNTech","geo":null,"retweeted":false,"in_reply_to_screen_name":null,"possibly_sensitive":false,"truncated":false,"lang":"en","entities":{"urls":[{"display_url":"cnn.it\/1bWid4q","expanded_url":"http:\/\/cnn.it\/1bWid4q","indices":[79,101],"url":"http:\/\/t.co\/TMUtbF80Kp"}],"hashtags":[],"user_mentions":[{"id":42703075,"indices":[106,114],"screen_name":"cnntech","id_str":"42703075","name":"cnntech"}],"symbols":[]},"in_reply_to_status_id_str":null,"id":406951229278146560,"in_reply_to_user_id_str":null,"source":"<a href=\"http:\/\/www.hootsuite.com\" rel=\"nofollow\">HootSuite<\/a>","favorited":false,"in_reply_to_status_id":null,"retweet_count":112,"in_reply_to_user_id":null,"created_at":"Sun Dec 01 01:01:48 +0000 2013","favorite_count":59,"id_str":"406951229278146560","place":null,"user":{"location":"","default_profile":false,"profile_background_tile":false,"statuses_count":36621,"lang":"en","profile_link_color":"004287","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/759251\/1384971184","id":759251,"following":null,"favourites_count":4,"protected":false,"profile_text_color":"000000","contributors_enabled":false,"verified":true,"description":"Bringing you breaking news and the most talked about stories. Join the conversation and let’s connect!","profile_sidebar_border_color":"000000","name":"CNN","profile_background_color":"323232","created_at":"Fri Feb 09 00:35:02 +0000 2007","default_profile_image":false,"followers_count":11060197,"profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/378800000049679889\/9097753c470683f49aa12a6c15eba5c7_normal.jpeg","geo_enabled":false,"profile_background_image_url":"http:\/\/a0.twimg.com\/profile_background_images\/664730338\/60cc7d1f1b1a22a87ccccef026e15949.gif","profile_background_image_url_https":"https:\/\/si0.twimg.com\/profile_background_images\/664730338\/60cc7d1f1b1a22a87ccccef026e15949.gif","follow_request_sent":null,"entities":{"description":{"urls":[]},"url":{"urls":[{"display_url":"cnn.com","expanded_url":"http:\/\/www.cnn.com","indices":[0,22],"url":"http:\/\/t.co\/Db6JkaxJ9R"}]}},"url":"http:\/\/t.co\/Db6JkaxJ9R","utc_offset":-18000,"time_zone":"Eastern Time (US & Canada)","notifications":null,"profile_use_background_image":true,"friends_count":818,"profile_sidebar_fill_color":"EEEEEE","screen_name":"CNN","id_str":"759251","profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/378800000049679889\/9097753c470683f49aa12a6c15eba5c7_normal.jpeg","is_translator":false,"listed_count":88693},"coordinates":null},{"contributors":null,"text":"Will online classes make professors extinct? \nhttp:\/\/t.co\/g20MbYagb9 via @CNNOpinion","geo":null,"retweeted":false,"in_reply_to_screen_name":null,"possibly_sensitive":false,"truncated":false,"lang":"en","entities":{"urls":[{"display_url":"cnn.it\/1b4VUbw","expanded_url":"http:\/\/cnn.it\/1b4VUbw","indices":[46,68],"url":"http:\/\/t.co\/g20MbYagb9"}],"hashtags":[],"user_mentions":[{"id":259074538,"indices":[73,84],"screen_name":"CNNOpinion","id_str":"259074538","name":"CNN Opinion"}],"symbols":[]},"in_reply_to_status_id_str":null,"id":406921147427852288,"in_reply_to_user_id_str":null,"source":"<a href=\"http:\/\/www.hootsuite.com\" rel=\"nofollow\">HootSuite<\/a>","favorited":false,"in_reply_to_status_id":null,"retweet_count":186,"in_reply_to_user_id":null,"created_at":"Sat Nov 30 23:02:16 +0000 2013","favorite_count":98,"id_str":"406921147427852288","place":null,"user":{"location":"","default_profile":false,"profile_background_tile":false,"statuses_count":36621,"lang":"en","profile_link_color":"004287","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/759251\/1384971184","id":759251,"following":null,"favourites_count":4,"protected":false,"profile_text_color":"000000","contributors_enabled":false,"verified":true,"description":"Bringing you breaking news and t
11-30 22:54:52.273: W/System.err(18610):    at com.android.volley.toolbox.JsonObjectRequest.parseNetworkResponse(JsonObjectRequest.java:73)
11-30 22:54:52.273: W/System.err(18610):    at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:116)
11-30 22:54:52.293: W/System.err(18610): Caused by: org.json.JSONException: Value [{"contributors":null,"text":"18-propeller copter might be the future of personal air travel, inventors say.\nhttp:\/\/t.co\/TMUtbF80Kp via @CNNTech","geo":null,"retweeted":false,"in_reply_to_screen_name":null,"possibly_sensitive":false,"truncated":false,"lang":"en","entities":{"urls":[{"display_url":"cnn.it\/1bWid4q","expanded_url":"http:\/\/cnn.it\/1bWid4q","indices":[79,101],"url":"http:\/\/t.co\/TMUtbF80Kp"}],"hashtags":[],"user_mentions":[{"id":42703075,"indices":[106,114],"screen_name":"cnntech","id_str":"42703075","name":"cnntech"}],"symbols":[]},"in_reply_to_status_id_str":null,"id":406951229278146560,"in_reply_to_user_id_str":null,"source":"<a href=\"http:\/\/www.hootsuite.com\" rel=\"nofollow\">HootSuite<\/a>","favorited":false,"in_reply_to_status_id":null,"retweet_count":112,"in_reply_to_user_id":null,"created_at":"Sun Dec 01 01:01:48 +0000 2013","favorite_count":59,"id_str":"406951229278146560","place":null,"user":{"location":"","default_profile":false,"profile_background_tile":false,"statuses_count":36621,"lang":"en","profile_link_color":"004287","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/759251\/1384971184","id":759251,"following":null,"favourites_count":4,"protected":false,"profile_text_color":"000000","contributors_enabled":false,"verified":true,"description":"Bringing you breaking news and the most talked about stories. Join the conversation and let’s connect!","profile_sidebar_border_color":"000000","name":"CNN","profile_background_color":"323232","created_at":"Fri Feb 09 00:35:02 +0000 2007","default_profile_image":false,"followers_count":11060197,"profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/378800000049679889\/9097753c470683f49aa12a6c15eba5c7_normal.jpeg","geo_enabled":false,"profile_background_image_url":"http:\/\/a0.twimg.com\/profile_background_images\/664730338\/60cc7d1f1b1a22a87ccccef026e15949.gif","profile_background_image_url_https":"https:\/\/si0.twimg.com\/profile_background_images\/664730338\/60cc7d1f1b1a22a87ccccef026e15949.gif","follow_request_sent":null,"entities":{"description":{"urls":[]},"url":{"urls":[{"display_url":"cnn.com","expanded_url":"http:\/\/www.cnn.com","indices":[0,22],"url":"http:\/\/t.co\/Db6JkaxJ9R"}]}},"url":"http:\/\/t.co\/Db6JkaxJ9R","utc_offset":-18000,"time_zone":"Eastern Time (US & Canada)","notifications":null,"profile_use_background_image":true,"friends_count":818,"profile_sidebar_fill_color":"EEEEEE","screen_name":"CNN","id_str":"759251","profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/378800000049679889\/9097753c470683f49aa12a6c15eba5c7_normal.jpeg","is_translator":false,"listed_count":88693},"coordinates":null},{"contributors":null,"text":"Will online classes make professors extinct? \nhttp:\/\/t.co\/g20MbYagb9 via @CNNOpinion","geo":null,"retweeted":false,"in_reply_to_screen_name":null,"possibly_sensitive":false,"truncated":false,"lang":"en","entities":{"urls":[{"display_url":"cnn.it\/1b4VUbw","expanded_url":"http:\/\/cnn.it\/1b4VUbw","indices":[46,68],"url":"http:\/\/t.co\/g20MbYagb9"}],"hashtags":[],"user_mentions":[{"id":259074538,"indices":[73,84],"screen_name":"CNNOpinion","id_str":"259074538","name":"CNN Opinion"}],"symbols":[]},"in_reply_to_status_id_str":null,"id":406921147427852288,"in_reply_to_user_id_str":null,"source":"<a href=\"http:\/\/www.hootsuite.com\" rel=\"nofollow\">HootSuite<\/a>","favorited":false,"in_reply_to_status_id":null,"retweet_count":186,"in_reply_to_user_id":null,"created_at":"Sat Nov 30 23:02:16 +0000 2013","favorite_count":98,"id_str":"406921147427852288","place":null,"user":{"location":"","default_profile":false,"profile_background_tile":false,"statuses_count":36621,"lang":"en","profile_link_color":"004287","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/759251\/1384971184","id":759251,"following":null,"favourites_count":4,"protected":false,"profile_text_color":"000000","contributors_enabled":false,"verified":true,"description":"Bringing you breaking news and the most talked about
11-30 22:54:52.293: W/System.err(18610):    at org.json.JSON.typeMismatch(JSON.java:111)
11-30 22:54:52.293: W/System.err(18610):    at org.json.JSONObject.<init>(JSONObject.java:158)
11-30 22:54:52.293: W/System.err(18610):    at org.json.JSONObject.<init>(JSONObject.java:171)
11-30 22:54:52.293: W/System.err(18610):    at com.android.volley.toolbox.JsonObjectRequest.parseNetworkResponse(JsonObjectRequest.java:68)
11-30 22:54:52.293: W/System.err(18610):    ... 1 more
11-30 22:56:51.289: W/IInputConnectionWrapper(18610): setComposingText on inactive InputConnection

这是java文件。

更新TweetRequest.java

public class TweetsRequest extends JsonArrayRequest {

public TweetsRequest(String url, Listener<JSONArray> listener, ErrorListener errorListener,
        List<NameValuePair> params) {
    super(url + "?" + URLEncodedUtils.format(params, "UTF-8"), listener, errorListener);
}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    Map<String, String> headers = new HashMap<String, String>();
    String auth = "Bearer " + TwitterValues.ACCESS_TOKEN;
    headers.put("Authorization", auth);
    return headers;
}
}

更新TweetLoader.java

public class TweetLoader implements OnEndReachedListener {

private static final String LIST_URL = "https://api.twitter.com/1.1/statuses/user_timeline.json";
protected static final String TAG = TweetLoader.class.getSimpleName();
private ArrayAdapter<JSONObject> tweetAdapter;
private TweetJsonListener mDownListener = new TweetJsonListener();
private String query = "cnn";
private Activity activity;

public TweetLoader(ArrayAdapter<JSONObject> tweetAdapter, Activity activity) {
    this.tweetAdapter = tweetAdapter;
    this.activity = activity;
}

public void setQuery(String query) {
    tweetAdapter.clear();
    this.query = query;
    onEndReached();
}

@Override
public void onEndReached() {
    activity.setProgressBarIndeterminate(true);
    activity.setProgressBarIndeterminateVisibility(true);
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("screen_name", "cnn"));

    MainActivity.mRequestQueue.add(new TweetsRequest(LIST_URL, mDownListener, new ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.w(TAG, "Error with request");
            error.printStackTrace();
        }
    }, params));
}

private class TweetJsonListener implements Listener<JSONArray> {

    public void onResponse(JSONObject response) {
        JSONObject jsonObject = null;
        JSONArray tweets = response.optJSONArray("statuses");
        int count = tweets != null ? tweets.length() : 0;
        for (int i = 0; i < count; i++) {
            jsonObject = tweets.optJSONObject(i);
            if (jsonObject != null) {
                tweetAdapter.add(jsonObject);
            }
        }
        activity.setProgressBarIndeterminateVisibility(false);
    }

    @Override
    public void onResponse(JSONArray arg0) {
        // TODO Auto-generated method stub

    }
}
}

TweetAdapter.java

public class TweetAdapter extends ArrayAdapter<JSONObject> {

private static final String TAG = TweetAdapter.class.getSimpleName();

public TweetAdapter(Context context) {
    super(context, 0);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.twitter_item, null);
        holder = new ViewHolder();
        holder.imageView = (NetworkImageView) convertView.findViewById(R.id.profile_image);
        holder.nameView = (TextView) convertView.findViewById(R.id.name);
        holder.textView = (TextView) convertView.findViewById(R.id.text);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    JSONObject currentItem = getItem(position);
    if (currentItem.length() == 0) {
        holder.nameView.setText(R.string.loading);
        holder.textView.setText("");
        holder.imageView.setImageResource(R.drawable.ic_launcher);
    } else {
        try {
            JSONObject user = currentItem.getJSONObject("user");
            holder.nameView.setText(user.optString("name", "<No name>"));
            holder.imageView.setImageUrl(user.getString("profile_image_url"), MainActivity.mImageLoader);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        holder.textView.setText(currentItem.optString("text", "<No text>"));
    }
    return convertView;
}

private static class ViewHolder {
    private NetworkImageView imageView;
    private TextView nameView;
    private TextView textView;
}

}

1 个答案:

答案 0 :(得分:0)

您没有发布TweetRequest类的实现,但是如果我必须做出有根据的猜测,我猜它是从JsonRequest类继承而自动转换字符串响应进入JSON 对象

问题是,您收到的回复是JSON 数组

因此,如果我的猜测是正确的,那么您的TweetRequest应该继承JsonArrayRequest

我是否正确阅读了情况?

编辑:

好的,尝试这个怎么样:

而不是将JsonObject转换为JsonArray,而是将您的请求作为数组请求:

public class TweetsRequest extends JsonArrayRequest {
    // basically the same implementation you have now
}

您需要更新您的听众,因为现在响应为JsonArray

编辑2:

您似乎已经遗漏了JSONObject请求和听众。这应该是您的TweetJsonListener - 请注意我只使用正确的方法覆盖并将您的实现粘贴到其中。我没有验证你的逻辑

private class TweetJsonListener implements Listener<JSONArray> {

    @Override
    public void onResponse(JSONArray response) {
        JSONObject jsonObject = null;
        JSONArray tweets = response.optJSONArray("statuses");
        int count = tweets != null ? tweets.length() : 0;
        for (int i = 0; i < count; i++) {
            jsonObject = tweets.optJSONObject(i);
        if (jsonObject != null) {
            tweetAdapter.add(jsonObject);
        }

        activity.setProgressBarIndeterminateVisibility(false);

    }
}