2013-07-20 204 views
0

我需要解析Twitter用户提要,我想从JSON字符串中生成JSON对象。我正确地能够得到json字符串,但是当我试图从中创建JSON对象时,它显示了一个JSONException。这是我尝试的代码。JSONObject从字符串错误

package com.heath_bar.twitter; 

import java.io.BufferedReader; 
import java.io.InputStream; 
import java.io.InputStreamReader; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.StringEntity; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.params.BasicHttpParams; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.app.Activity; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Base64; 
import android.util.Log; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.TextView; 

public class MainActivity extends Activity { 

    final String URL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=*******"; 
    final String APIKEY = "***********************"; 
    final String APISECRET = "*********************"; 
    final String BearerToken = "AAAAAAAAAAAAAAAAAAAAAMRF***************************"; 

    JSONObject jsonObj = null; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     Button btn_get_feed = (Button) findViewById(R.id.btn_get_feed); 
     btn_get_feed.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       String bearer_token = BearerToken; 
       new GetFeedTask().execute(bearer_token, URL); 
      } 
     }); 
    } 

    protected class GetFeedTask extends AsyncTask<String, Void, String> { 

     @Override 
     protected String doInBackground(String... params) { 

      try { 
       DefaultHttpClient httpclient = new DefaultHttpClient(
         new BasicHttpParams()); 
       HttpGet httpget = new HttpGet(params[1]); 
       httpget.setHeader("Authorization", "Bearer " + params[0]); 
       httpget.setHeader("Content-type", "application/json"); 

       InputStream inputStream = null; 
       HttpResponse response = httpclient.execute(httpget); 
       HttpEntity entity = response.getEntity(); 
       inputStream = entity.getContent(); 
       BufferedReader reader = new BufferedReader(new InputStreamReader(
         inputStream, "iso-8859-1"), 8); 
       StringBuilder sb = new StringBuilder(); 
       String line = null; 
       while ((line = reader.readLine()) != null) { 
        sb.append(line + "\n"); 
       } 
       inputStream.close(); 
       return sb.toString(); 
      } catch (Exception e) { 
       Log.e("GetFeedTask", "Error:" + e.getMessage()); 
       return null; 
      } 
     } 

     @Override 
     protected void onPostExecute(String jsonText) { 
      try { 
       TextView txt = (TextView) findViewById(R.id.txt_feed); 
       txt.setText(jsonText); // this is showing the JSON string 

       try { 
        jsonObj = new JSONObject(jsonText); 
        Log.d("status_success", "Successfully created JSON object"); 
       } catch (JSONException e) { 
        Log.e("JSON Parser", "Error parsing data " + e.toString()); 
       } 
      } catch (Exception e) { 
       Log.e("GetFeedTask", "Error:" + e.getMessage()); 
      } 
     } 
    } 

} 
+2

这将是与twitter4j库,它封装了API调用和分析你的答复更容易。 – brillenheini

+0

我需要解析今天的feed,profile-image,feed创建8个用户的时间。 'twitter4j'可以提供更多的支持而不是手动完成?或者手动做就足够了?需要提及的是,我正在使用“仅应用程序认证”。 –

+0

twitter4j不能做的比官方API可能的更多,因为它正在使用它。这只是少一点工作。 – brillenheini

回答

1

I need to parse twitter feed.......

尝试JSONArray,而不是JSONObject

JSONArray jsonArray = new JSONArray(jsonText); 

Twitter的REST API 1.1进料以与阵列节点开始。可以找到示例JSON提要here

[ 
    { 
    "coordinates": null, 
    "favorited": false, 
    "truncated": false, 
    "created_at": "Wed Aug 29 17:12:58 +0000 2012", 
    "id_str": "240859602684612608", 
    "entities": { 
     "urls": [ 
     { 
      "expanded_url": "https://dev.twitter.com/blog/twitter-certified-products", 
      "url": "https://t.co/MjJ8xAnT", 
      "indices": [ 
      52, 
      73 
      ], 
      "display_url": "dev.twitter.com/blog/twitter-c\u2026" 
     } 
     ], 
     "hashtags": [ 

     ], 
     "user_mentions": [ 

     ] 
    }, 
    "in_reply_to_user_id_str": null, 
    "contributors": null, 
    "text": "Introducing the Twitter Certified Products Program: https://t.co/MjJ8xAnT", 
    "retweet_count": 121, 
    "in_reply_to_status_id_str": null, 
    "id": 240859602684612608, 
    "geo": null, 
    "retweeted": false, 
    "possibly_sensitive": false, 
    "in_reply_to_user_id": null, 
    "place": null, 
    "user": { 
     "profile_sidebar_fill_color": "DDEEF6", 
     "profile_sidebar_border_color": "C0DEED", 
     "profile_background_tile": false, 
     "name": "Twitter API", 
     "profile_image_url": "http://a0.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_normal.png", 
     "created_at": "Wed May 23 06:01:13 +0000 2007", 
     "location": "San Francisco, CA", 
     "follow_request_sent": false, 
     "profile_link_color": "0084B4", 
     "is_translator": false, 
     "id_str": "6253282", 
     "entities": { 
     "url": { 
      "urls": [ 
      { 
       "expanded_url": null, 
       "url": "http://dev.twitter.com", 
       "indices": [ 
       0, 
       22 
       ] 
      } 
      ] 
     }, 
     "description": { 
      "urls": [ 

      ] 
     } 
    } 
] 
1

Twitter推文出现在每个JSONObject的“text”标签下。 访问每个JSON对象从JSON数组如下

ArrayList<String> tweets=new ArrayList<String>(); 
JSONArray array =new JSONArray(jsonText); 
        for(int i=0;i<array.length();i++){ 
         JSONObject obj=array.getJSONObject(i); 
         String text=obj.getString("text"); 
         tweets.add(text); 
         ArrayAdapter<String> adapter=new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_list_item_1,tweets); 
         lv.setAdapter(adapter);// displaying in a listview 
        }