2013-04-14 32 views
0

我在從twitter搜索feed解析json時遇到了問題。例如搜索網址是:json twitter在Android搜索解析中的提要

https://search.twitter.com/search.json?q=android 

Here is a link to the search

我想在JSON數據 「結果」 的數組。我的代碼獲取JSON和解析:

StringBuilder tweetFeedBuilder = new StringBuilder(); 
HttpClient tweetClient = new DefaultHttpClient(); 

//pass search URL string to fetch 
HttpGet tweetGet = new HttpGet(searchURL); 

//execute request 
HttpResponse tweetResponse = tweetClient.execute(tweetGet); 
//check status, only proceed if ok 
StatusLine searchStatus = tweetResponse.getStatusLine(); 
if (searchStatus.getStatusCode() == 200) { 
    //get the response 
    HttpEntity tweetEntity = tweetResponse.getEntity(); 
    InputStream tweetContent = tweetEntity.getContent(); 
    //process the results 
    InputStreamReader tweetInput = new InputStreamReader(tweetContent); 
    BufferedReader tweetReader = new BufferedReader(tweetInput); 

    while ((lineIn = tweetReader.readLine()) != null) 
    { 
     tweetFeedBuilder.append(lineIn); 
    } 

    try{ 
     // A Simple JSONObject Creation 
     JSONObject json=new JSONObject(tweetFeedBuilder); 
     Log.i("Tweets","<jsonobject>\n"+json.toString()+"\n</jsonobject>"); 

     String str1 = "result"; 
     JSONArray jarray = json.getJSONArray(str1); 

     for(int i = 0; i < jarray.length(); i++){ 

      JSONObject c = jarray.getJSONObject(i); 
      String id = c.getString(TWEET_ID); 
      String text = c.getString(TWEET_TEXT); 
     } 
    } 
    catch(JSONException jexp){ 
     jexp.printStackTrace(); 
    } 

創建JSON對象後,JSONArray給人創造的錯誤並且去catch塊。其實我想從JSON數據中獲取「結果」數組。

但創建時出錯。我只想從JSON數據中獲取user_id和文本。 我在android平臺和eclipse sdk上工作。

+3

在「str1」中嘗試「結果」而不是「結果」。 – eightx2

回答

1

正如在評論中已經提到的那樣,您正在使用錯誤的密鑰。它應該是

String str1 = "results"; // you are using result 
0

(只是闡述我的意見......)

如果在JSON響應仔細一看,結果陣列的關鍵不是result,但results。因此,你應該這樣做,得到JSONArray:

JSONArray jarray = json.getJSONArray("results"); 

另外,我注意到你想獲取每個陣列項目「USER_ID」和「文本」。請務必爲用戶使用正確的密鑰:from_user_id

+0

感謝哥們,我明白了 –