首页 > 解决方案 > How to extract field from Google books api using GSON and Jsoup

问题描述

I'm new on here and I'm trying to extract titles and authors from a Google API by ISBN.

Here is the code:

 try {
     Document   docKb = Jsoup.connect("https://www.googleapis.com/books/v1/volumes?q=isbn:0735619670").ignoreContentType(true).get();
        String json = docKb.body().text();

        Gson gson = new Gson();
        //new Gson().toJson(new HashMap(map)); 
        Map<String, Object> asMap = gson.fromJson(json, Map.class);
        List<Map<String, Object>> items = (List) asMap.get("items");
        //  Map<String, Object> e = (Map) error.get("error")
        for (Map<String, Object> item : items) {
            if (item.containsKey("title") && item.containsKey("authors")) {
                String title = (String) item.get("title");
                System.out.println("if Título: " + title);
            } else {
                System.out.println("Título: " + item.get("title") + "\n");
                System.out.println("Autor: " + item.get("authors"));    

       }
       }
        System.out.println("items: "+ items );

    }catch(IOException e){
        e.printStackTrace();            
    }

It didn't work... the values were null for title and author but in the list 'items' it has scraped everything from the API.

标签: javajsonapigsonjsoup

解决方案


Whats going on here is a simple JSON parsing error. You are not giving the gson the correct class. Put simply, this JSON is not a Map. Instead, it is an object, that contains:

String kind;
int totalItems;
Object items;

Below I have provided the full code required to correctly parse this JSON (assuming that you are able to obtain the JSON string correctly.

class ClassWhatever {
    public static void main(String[] args) {
        String url = "https://www.googleapis.com/books/v1/volumes?q=isbn:0735619670";
        // Assuming that you do in fact have the JSON string...
        String json = "the correct json";

        Container fullJsonObject = new Gson().fromJson(json, Container.class);

        for (Item i : fullJsonObject.items) {
            System.out.println(i.volumeInfo.authors[0]);
        }
    }

    private class Container {
        String kind;
        int totalItems;
        Item[] items;
    }

    private class Item {
        String kind;
        String id;
        String etag;
        ///blah
        VolumeInfo volumeInfo;
        String publisher;
        ///etc.

    }

    private class VolumeInfo {
        String title;
        String[] authors;
    }
}

Output:

Steve McConnell
Steve McConnell

Notes:

You only need to add the fields that you want. For instance, if you did not need the String kind, just don't put it in your Container class. I left out many fields for brevity, but of course put them in if you need them.

Also, I chose to use Arrays instead of lists. They are fully interchangeable as long as you format your code correctly.


推荐阅读