2016-11-17 94 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层次正确,我在呼唤一个非存在的元素