无法在JSONObject中解析JSONArray

时间:2016-11-17 16:27:52

标签: java android json

由于某些原因,我可以读回整个数组,但是当我尝试选择一个段时,它不会让我看到数组长度等于1的数组中的段过去,就像它们被压扁了一样一个要素。这是我的代码:

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");
                    }
                }
     

result = name;

3 个答案:

答案 0 :(得分:1)

我刚刚拨打了您在代码https://www.googleapis.com/books/v1/volumes?q=lTrump&maxResults=1中填写的网址以及&#39;项目&#39;无论如何,数组的长度仅为1。尝试从网址中删除&amp; maxResults = 1?

因此请使用此网址https://www.googleapis.com/books/v1/volumes?q=lTrump

答案 1 :(得分:0)

这很简单......改变:

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

为:

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

您将获得多个项目

答案 2 :(得分: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层次结构,我正在调用一个不存在的元素