Notes on implementing google books api in java okhttp and gson versions and okhttp and jackson versions

It is a memo when I made a program application to register a book that I have on the web read with a barcode reader

okhttp and gson version

Overview

java

in maven

gson is a library for converting Java objects and JSON format data to each other.

gson version 2.8.6 used Site with explanation https://qiita.com/naoi/items/6b184700b2a41fb46356

OkHttp is an efficient HTTP client by default

Use okhttp version 3.7.0 Explanation site https://square.github.io/okhttp/

   <dependency>
  		<groupId>com.google.code.gson</groupId>
  		<artifactId>gson</artifactId>
  		<version>2.8.6</version>
  	</dependency> 
    <dependency>
  		<groupId>com.squareup.okhttp3</groupId>
  		<artifactId>okhttp</artifactId>
  		<version>3.7.0</version>
  	</dependency>

google books api Official page https://developers.google.com/books/

Screenshot from Gyazo

This time, the code read by isbn with the barcode reader is sent as a request, so the code below is used.

https://www.googleapis.com/books/v1/volumes?q=isbn:Isbn code at the back
//It looks like below
https://www.googleapis.com/books/v1/volumes?q=isbn:9784844336778


json returned after sending a request with google books api

I'm not sure to be honest If there is a way to understand the hierarchy, please post it

// 20200101165936
// https://www.googleapis.com/books/v1/volumes?q=isbn:9784844336778

{
  "kind": "books#volumes",
  "totalItems": 1,
  "items": [
    {
      "kind": "books#volume",
      "id": "FQKOBAAAQBAJ",
      "etag": "YZLyBEypyf4",
      "selfLink": "https://www.googleapis.com/books/v1/volumes/FQKOBAAAQBAJ",
      "volumeInfo": {
        "title": "A refreshing introduction to Java Practical Edition 2nd Edition",
        "authors": [
          "Kiyotaka Nakayama"
        ],
        "publisher": "Impress Corporation",
        "publishedDate": "2014-09-22",
        "description": "A revised version of Java 8's featured features such as lambda expressions and date APIs has been expanded, and agile-related and design patterns have been thoroughly strengthened! As with the sister book "Introduction to Java", the explanation will proceed while answering "Why?" Firmly, so knowledge essential for mastering Java at work, such as regular expressions, collections, database linkage, refactoring, parallel processing, etc. However, it is refreshing, fun, and easy to learn. Recommended for those who have understood the basic grammar and object-oriented concepts and want to take it even further. Issue",
        "industryIdentifiers": [
          {
            "type": "ISBN_13",
            "identifier": "9784844336778"
          },
          {
            "type": "ISBN_10",
            "identifier": "4844336770"
          }
        ],
        "readingModes": {
          "text": false,
          "image": true
        },
        "pageCount": 628,
        "printType": "BOOK",
        "categories": [
          "Computers"
        ],
        "maturityRating": "NOT_MATURE",
        "allowAnonLogging": true,
        "contentVersion": "2.3.0.0.preview.1",
        "panelizationSummary": {
          "containsEpubBubbles": false,
          "containsImageBubbles": false
        },
        "imageLinks": {
          "smallThumbnail": "http://books.google.com/books/content?id=FQKOBAAAQBAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
          "thumbnail": "http://books.google.com/books/content?id=FQKOBAAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
        },
        "language": "ja",
        "previewLink": "http://books.google.co.jp/books?id=FQKOBAAAQBAJ&printsec=frontcover&dq=isbn:9784844336778&hl=&cd=1&source=gbs_api",
        "infoLink": "https://play.google.com/store/books/details?id=FQKOBAAAQBAJ&source=gbs_api",
        "canonicalVolumeLink": "https://play.google.com/store/books/details?id=FQKOBAAAQBAJ"
      },
      "saleInfo": {
        "country": "JP",
        "saleability": "FOR_SALE",
        "isEbook": true,
        "listPrice": {
          "amount": 2596.0,
          "currencyCode": "JPY"
        },
        "retailPrice": {
          "amount": 2336.0,
          "currencyCode": "JPY"
        },
        "buyLink": "https://play.google.com/store/books/details?id=FQKOBAAAQBAJ&rdid=book-FQKOBAAAQBAJ&rdot=1&source=gbs_api",
        "offers": [
          {
            "finskyOfferType": 1,
            "listPrice": {
              "amountInMicros": 2596000000,
              "currencyCode": "JPY"
            },
            "retailPrice": {
              "amountInMicros": 2336000000,
              "currencyCode": "JPY"
            }
          }
        ]
      },
      "accessInfo": {
        "country": "JP",
        "viewability": "PARTIAL",
        "embeddable": true,
        "publicDomain": false,
        "textToSpeechPermission": "ALLOWED",
        "epub": {
          "isAvailable": false
        },
        "pdf": {
          "isAvailable": true,
          "acsTokenLink": "http://books.google.co.jp/books/download/%E3%82%B9%E3%83%83%E3%82%AD%E3%83%AA%E3%82%8F%E3%81%8B%E3%82%8BJava%E5%85%A5%E9%96%80_%E5%AE%9F%E8%B7%B5-sample-pdf.acsm?id=FQKOBAAAQBAJ&format=pdf&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
        },
        "webReaderLink": "http://play.google.com/books/reader?id=FQKOBAAAQBAJ&hl=&printsec=frontcover&source=gbs_api",
        "accessViewStatus": "SAMPLE",
        "quoteSharingAllowed": false
      },
      "searchInfo": {
        "textSnippet": "A revised version of Java 8's featured features such as lambda expressions and date APIs has been expanded, and agile-related and design patterns have been thoroughly strengthened! Like the sister book "Introduction to Java", "Why?"..."
      }
    }
  ]
}

Generate JSON model class (pojo)

https://qiita.com/riversun/items/cdd990e96c2bbf9cb043 On this page, I referred to Automatically generate model class (pojo) using jsonschema2pojo.

Generated class file

Screenshot from Gyazo

The contents of the Model class

Screenshot from Gyazo

@SerializeName ("name") @Expose public type name

Since items is "items": [], it will be List items = null ;.

Screenshot from Gyazo

Caution

The model class is automatically generated, but it may be insufficient, so please make the one that is not generated by yourself.

java main code

package main;

import java.io.IOException;
import java.util.List;

import com.example.qson.Item;
import com.example.qson.ListPrice;
import com.example.qson.Model;
import com.example.qson.SaleInfo;
import com.example.qson.VolumeInfo;
import com.google.gson.Gson;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class main {

    public static final String url = "https://www.googleapis.com/books/v1/volumes?q=isbn:";

    public static void main(String[] args) {
        //isbn code
        Long isbn = 9784844336778L;

        //Hold json
        String json = "";

        OkHttpClient okHttpClient;

        okHttpClient = new OkHttpClient();

        Request.Builder builder = new Request.Builder();

        //Insert the address to send the request with url
        builder.url(url + isbn);

        Request request = builder.build();

        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            //I have the json information returned from the web api as mentioned above on the json here
            json = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Gson gson = new Gson();

        Model models = gson.fromJson(json, Model.class);
        List<Item> items2 = models.items;
        VolumeInfo  volumeInfo = items2.get(0).volumeInfo;
        ImageLinks imageLinks = volumeInfo.imageLinks;

        SaleInfo saleInfo = items2.get(0).saleInfo;
        ListPrice listPrice = saleInfo.listPrice;

        //When title is written from model class
        //items class is List<Item>Because it is a type.get()Attach
        System.out.println(models.items.get(0).volumeInfo.title);//title

        //When the model class is changed to the volumeinfo class and displayed
        System.out.println("title: "    + volumeInfo.title);//title
        System.out.println("author: "   + volumeInfo.authors);//author
        System.out.println("Publication date: "   + volumeInfo.publishedDate);//publishedDate
        System.out.println("the publisher: "   + volumeInfo.publisher);//publisher
        System.out.println("List price:"      + listPrice.amount);
        System.out.println("Description:"     + volumeInfo.description);//description
        System.out.println("number of pages:" + volumeInfo.pageCount);//pageCount
        System.out.println("Small thumbnail:" + imageLinks.smallThumbnail);//smallThumbnail
        System.out.println("thumbnail:"         + imageLinks.thumbnail);//thumbnail

    }
}

Execution result Screenshot from Gyazo

I was able to go to the feeling

okhttp and jackson versions

Overview

java

in maven

OkHttp is an efficient HTTP client by default

Use okhttp version 3.7.0 Explanation site https://square.github.io/okhttp/

jackson

jackson-core version: 2.10.0 jackson-annotations version: 2.10.0 jackson-databind version: 2.10.0

Is put in

  <dependency>
  		<groupId>com.fasterxml.jackson.core</groupId>
  		<artifactId>jackson-core</artifactId>
  		<version>2.10.0</version>
  	</dependency>
  	<dependency>
  		<groupId>com.fasterxml.jackson.core</groupId>
  		<artifactId>jackson-annotations</artifactId>
  		<version>2.10.0</version>
  	</dependency>
  	<dependency>
  		<groupId>com.fasterxml.jackson.core</groupId>
  		<artifactId>jackson-databind</artifactId>
  		<version>2.10.0</version>
  	</dependency>
    <dependency>
  		<groupId>com.squareup.okhttp3</groupId>
  		<artifactId>okhttp</artifactId>
  		<version>3.7.0</version>
  	</dependency>

java main

import java.io.IOException;
import java.sql.Date;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class main {
    public static final String url = "https://www.googleapis.com/books/v1/volumes?q=isbn:";

    public static void main(String[] args) {
        //TODO auto-generated method stub
        Long isbn = 9784295007807L;

        //Hold json
        String json ="";

        //Book title
        String title = "";
        //author
        String author = "";
        //Publication date
        Date publishedDate = null;
        String day = "";
        //the publisher
        String publisher = "";
        //List price
        Integer listPrice = null;
        //Explanatory text
        String description = "";
        //number of pages
        Integer pageCount = null;
        //small thumbnail
        String smallThumbnail ="";
        //thumbnail
        String thumbnail = "";


        OkHttpClient okHttpClient;

        okHttpClient = new OkHttpClient();

        Request.Builder builder = new Request.Builder();

        //Insert the address to send the request with url
        builder.url(url + isbn);

        Request request = builder.build();

        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            json = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //Display the contents of json
        System.out.println(json);

        //Processing to take out the contents of json from here and display it
        ObjectMapper mapper = new ObjectMapper();
        try {
            JsonNode node = mapper.readTree(json);

             //get("value")Value is json"title": "A refreshing introduction to Java Practical Edition 2nd Edition"
             //The title part will be the value
             //Since title is a String type, at the end.asText();Attach
             title =          node.get("items").get(0).get("volumeInfo").get("title").asText();
             author =         node.get("items").get(0).get("volumeInfo").get("authors").get(0).asText();
             publisher =      node.get("items").get(0).get("volumeInfo").get("publisher").asText();

             //Received as String day to convert publication date to Date type
             day = node.get("items").get(0).get("volumeInfo").get("publishedDate").textValue();

             //Convert string to sql type Date
             publishedDate =  Date.valueOf(day);

             //listPrice is an int type, so at the end.asInt();Attach
             listPrice =      node.get("items").get(0).get("saleInfo").get("listPrice").get("amount").asInt();
             description =    node.get("items").get(0).get("volumeInfo").get("description").asText();
             pageCount =      node.get("items").get(0).get("volumeInfo").get("pageCount").asInt();
             smallThumbnail = node.get("items").get(0).get("volumeInfo").get("imageLinks").get("smallThumbnail").asText();
             thumbnail =      node.get("items").get(0).get("volumeInfo").get("imageLinks").get("thumbnail").asText();

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

        }

        System.out.println("title: " +title);
        System.out.println("author: " +author);
        System.out.println("the publisher: "+publisher);
        System.out.println("Publication date: " + publishedDate);
        System.out.println("List price: " + listPrice + "Circle");
        System.out.println("Explanatory text: " + description);
        System.out.println("number of pages: " + pageCount);
        System.out.println("Small thumbnail: " + smallThumbnail);
        System.out.println("thumbnail: " +thumbnail);

    }

}

Screenshot from Gyazo

I was able to do it like that

Recommended Posts

Notes on implementing google books api in java okhttp and gson versions and okhttp and jackson versions
Create API using Retrofit2, Okhttp3 and Gson (Java)
Upload and download notes in java on S3
Notes on signal control in Java
Notes on Java path and Package
Notes on Java's Stream API and SQL
I tried Mastodon's Toot and Streaming API in Java
I tried using Google Cloud Vision API in Java
[Java] Convert JSON to Java and Java to JSON-How to use GSON and Jackson-
Notes on how to use regular expressions in Java
Zabbix API in Java
JSON in Java and Jackson Part 1 Return JSON from the server
How to call and use API in Java (Spring Boot)
Tips for using Salesforce SOAP and Bulk API in Java
Generate AWS Signature V4 in Java and request an API