本文介绍了只能在数组或java.lang.Iterable实例上进行迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我一直收到此错误,我正在尝试通过JSON从Twitter获得推文,并且似乎无法在"arr"上消除此问题.我需要做一个不同的for循环吗?我确实尝试过此方法,但它始终返回相同的错误.

Hi I keep getting this error, I'm trying to get tweets from twitter via JSON and cant seem to get rid of this on the "arr". Would I have to do a different for loop? I did try this but it keeps returning the same error.

 public ArrayList<Tweet> getTweets(String searchTerm, int page) {
      String searchUrl = 
            "http://search.twitter.com/search.json?q=@" 
            + searchTerm + "&rpp=100&page=" + page;

      ArrayList<Tweet> tweets = 
            new ArrayList<Tweet>();

      HttpClient client = new  DefaultHttpClient();
      HttpGet get = new HttpGet(searchUrl);

      ResponseHandler<String> responseHandler = 
            new BasicResponseHandler();

      String responseBody = null;
      try {
        responseBody = client.execute(get, responseHandler);
      } catch(Exception ex) {
        ex.printStackTrace();
      }

      JSONObject jsonObject = null;
      JSONParser parser = new JSONParser();

      try {
        Object obj = parser.parse(responseBody);
        jsonObject=(JSONObject)obj;
      }catch(Exception ex){
        Log.v("TEST","Exception: " + ex.getMessage());
      }

      JSONArray<Object> arr = null;

      try {
        Object j = jsonObject.get("results");
        arr = (JSONArray)j;
      } catch(Exception ex){
        Log.v("TEST","Exception: " + ex.getMessage());
      }

      for(Object t : arr) {
        Tweet tweet = new Tweet(
          ((JSONObject)t).get("from_user").toString(),
          ((JSONObject)t).get("text").toString(),
          ((JSONObject)t).get("profile_image_url").toString()
        );
        tweets.add(tweet);
      }

      return tweets;
    }

请帮助!

推荐答案

如异常所示,您只能在java.lang.Iterable实例上使用for每个循环进行迭代. JSONArray不是其中之一.

As the exception says, you can only iterate with the for each loop on instances of java.lang.Iterable. JSONArray is not one of them.

使用经典"循环:

for(int i = 0; i < arr.length(); i++) {
   JSONObject t = (JSONObject) arr.get(i);
   Tweet tweet = new Tweet(
     t.get("from_user").toString(),
     t.get("text").toString(),
     t.get("profile_image_url").toString()
   );
   tweets.add(tweet);
 }

这篇关于只能在数组或java.lang.Iterable实例上进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 10:31