2012-03-11 46 views
1

我有一個Twitter的飼料的URL,我已經創建了一個字符串,我想把它放在一個JSONArray,所以我可以回電各個項目。在這種情況下 - 「文本」。Android Twitter字符串到Json數組

Here's the json

這裏是我的代碼

try { 
    // Create a new HTTP Client 
    DefaultHttpClient defaultClient = new DefaultHttpClient(); 
    // Setup the get request 
    HttpGet httpGetRequest = new HttpGet(
     "https://api.twitter.com/1/statuses/user_timeline.json?screen_name=evostikleague&count=10"); 

    // Execute the request in the client 
    HttpResponse httpResponse = defaultClient.execute(httpGetRequest); 
    // Grab the response 
    BufferedReader reader = new BufferedReader(new InputStreamReader(
     httpResponse.getEntity().getContent(), "UTF-8")); 
    String json = reader.readLine(); 

    // Instantiate a JSON object from the request response 
    JSONObject obj = new JSONObject(json); 
    List<String> items = new ArrayList<String>(); 

    JSONArray jArray = obj.getJSONArray(json); 

    for (int i = 0; i < jArray.length(); i++) { 
     JSONObject oneObject = jArray.getJSONObject(i); 
     items.add(oneObject.getString("text")); 
     Log.i("items", "items"); 
    } 

    setListAdapter(new ArrayAdapter<String>(this, R.layout.single_item, 
     items)); 
    ListView list = getListView(); 
    list.setTextFilterEnabled(true); 

    list.setOnItemClickListener(new OnItemClickListener() { 

     public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, 
      long arg3) { 
     // TODO Auto-generated method stub 
     Toast.makeText(getApplicationContext(), 
       ((TextView) arg1).getText(), 1000).show(); 
     } 

    }); 

} catch (Exception e) { 
    // In your production code handle any errors and catch the individual exceptions 
    e.printStackTrace(); 
} 
+0

有什麼問題可以找到? – MByD 2012-03-11 14:05:25

+0

它不顯示我的列表視圖中的任何東西我在我的LogCat中得到一個JSONeexception。 – iamlukeyb 2012-03-11 14:15:26

回答

1

您正試圖解析響應爲JSONObject{}),而這是一個JSONArray[])。你或許應該刪除行:

// Instantiate a JSON object from the request response 
JSONObject obj = new JSONObject(json); 

相反,你需要:

JSONArray jArray = new JSONArray(json); 
+0

好吧我編輯它,現在只是得到紅十字它不喜歡json.getString字符串json = reader.readLine(); \t \t Log.v(json,「jsonfeed」); \t \t \t \t \t \t \t \t \t 列表\t項 =新的ArrayList (); \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t 爲\t(INT I = 0; I (這一點,R.layout。single_item,items)); – iamlukeyb 2012-03-11 14:26:21

+0

好吧,算出來,你是對的,但我也需要轉換成JSONArray JSONArray jArray = new JSONArray(json); – iamlukeyb 2012-03-11 14:29:56

+0

我的錯誤,請參閱我的修復程序。 – MByD 2012-03-11 14:30:35

0

我們需要JSON對象第一。例如,

JSONObject jsonObject = new JSONObject(resp); 

jsonObject可能包含其他JSON對象或JSON數組。如何轉換JSON取決於字符串。

JSONArray arr = jsonObject.getJSONArray("arraykey"); 

沒有與有關JSON字符串JSON陣列一些解釋一個完整的例子可以在http://www.hemelix.com/JSONHandling