2016-11-17 98 views
-1

由於某種原因,我可以將整個數組讀回來,但是當我嘗試選擇一個段時,它不讓我看到數組中的段過去,數組長度等於1,就像所有被壓扁成一個元素。這是我的代碼:解析JSONObject中的JSONArray問題

https://github.com/yehudaclinton/Mytest/blob/master/TestHTTP.java

  try { 
       Object obj = parser.parse(result); 
       JSONObject jsonObject = (JSONObject) obj; 
       JSONArray items = (JSONArray) jsonObject.get("items"); 
       Log.d(TAG, "items length: " + items.size());//for some reason is not more than 1 
       String name = ""; 
       //the the following is supposed to return just the title of book 
       for (int i = 0; i < items.size(); i++) { 
        JSONObject item = (JSONObject) items.get(i);//if 'i' equals more then one program crashes 
        if(item.get("title")!=null) {//only get the title 
         JSONObject theTitle = (JSONObject) item.get("title"); 
         name = (String) theTitle.get("title"); 
        } 
       } 

結果=名稱;

+0

什麼是堆棧跟蹤? –

回答

0

這是非常簡單的...改變:

https://www.googleapis.com/books/v1/volumes?q=lTrump&maxResults=1 

到:

https://www.googleapis.com/books/v1/volumes?q=lTrump&maxResults=[someNumber] 

,你會得到一個以上的項目

+0

當你有這樣的問題時,嘗試使用http://www.jsoneditoronline.org/或類似的東西。然後你可以檢查問題是在你的JSON響應還是代碼本身。 我打電話給你的Api終點,我只有一個項目...這是你的問題 –

1

我只是叫你的網址已經得到了你的代碼https://www.googleapis.com/books/v1/volumes?q=lTrump&maxResults=1,'items'數組只有長度爲1。嘗試從url中刪除& maxResults = 1?

所以使用這個網址,而不是https://www.googleapis.com/books/v1/volumes?q=lTrump

0

其實大家都錯過了,不過這裏是回答我的問題

   Object obj = parser.parse(result); 
       JSONObject jsonObject = (JSONObject) obj; 
       JSONArray items = (JSONArray) jsonObject.get("items"); 
       JSONObject first = (JSONObject) items.get(0); 
       JSONObject volumeInfo = (JSONObject) first.get("volumeInfo"); 
       String name = (String) volumeInfo.get("title"); 

我基本上沒有得到JSON層次正確,我在呼喚一個非存在的元素