简体   繁体   English

在循环中解析json时返回null - android

[英]return null while parsing json in loop - android

trying to parse "publisher" key from json object it is returning error but if I parse only "title" key it works fine 试图从json对象解析“publisher”键它返回错误,但如果我只解析“title”键它工作正常

public ArrayList<BookData> parseJSON(String jsonString){
        try{
            JSONObject obj = new JSONObject(jsonString);
            JSONArray jsonArray = obj.getJSONArray("items");
            for(int i=0;i<10;i++){
                JSONObject object = jsonArray.getJSONObject(i);
                JSONObject volumeInfo = object.getJSONObject("volumeInfo");
               //this title works fine
                String title = volumeInfo.getString("title");
               //this publisher is throwing null pointer exception
                String  publisher = volumeInfo.getString("publisher");
                //Log.v("testing title", publisher);
                list.add(new BookData(title, "publisher"));

            }
            return list;

        }catch (Exception e){e.printStackTrace();}
        return null;
    }

JSON is here: JSON在这里:

"volumeInfo":{  
            "title":"Organic Chemistry",
            "authors":[  
               "Jonathan Clayden",
               "Nick Greeves",
               "Stuart Warren"
            ],
            "publisher":"Oxford University Press"
            }

为发布者放置一个null检查器可能是你得到NullpointerException,希望它会帮助你

list.add(new BookData(title, "publisher")); replace this with below given code. 用下面给出的代码替换它。

list.add(new BookData(title, publisher));

From the documentation of getString you can see that: getString文档中可以看到:

throws NullPointerException - if the specified name doesn't have any mapping throws NullPointerException - 如果指定的名称没有任何映射

So if the title works fine, that means the publisher is not there in your JSON. 因此,如果title工作正常,则表示publisher者不在您的JSON中。 Check your Json String again. 再次检查您的Json字符串。

Hope this helps. 希望这可以帮助。

You have publisher in quotes when you add it to the array: list.add(new BookData(title, "publisher")) this passes in a string literal, you want to pass in the variable publisher. 将数据库添加到数组时,您将引号放在引号中:list.add(new BookData(title,“publisher”))这将传入字符串文字,您希望传入变量发布者。 So simply replace "publisher" in that line with publisher. 因此,只需将该行中的“publisher”替换为发布者即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM