简体   繁体   中英

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

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:

"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:

throws NullPointerException - if the specified name doesn't have any mapping

So if the title works fine, that means the publisher is not there in your JSON. Check your Json String again.

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. So simply replace "publisher" in that line with publisher.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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