LoginSignup
5
2

More than 3 years have passed since last update.

google books api をjavaで実装したときのメモ okhttp と gson バージョンと okhttp と jacksonバージョンです

Last updated at Posted at 2020-01-01

webで持っている本をバーコードリーダーで読み込んだものを登録するプログラムアプリを作ったときのメモです

okhttp と gson バージョン

概要

java

mavenで

gsonはJavaのオブジェクトとJSON形式のデータを相互で変換するためのライブラリ

gson バージョン 2.8.6使用
説明のあるサイト
https://qiita.com/naoi/items/6b184700b2a41fb46356

OkHttpはデフォルトで効率的なHTTPクライアント

okhttp バージョン 3.7.0使用
説明サイト
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

公式ページ
https://developers.google.com/books/

Screenshot from Gyazo

今回はバーコードリーダでisbnで読み込んだものをリクエストとして送信するので下のコードになります

https://www.googleapis.com/books/v1/volumes?q=isbn:一番後ろにisbnコード
//下のようになる
https://www.googleapis.com/books/v1/volumes?q=isbn:9784844336778


google books api でリクエストを送信し帰ってきたjson

正直いってよくわからないので
階層がわかる方法があればだれか載せてほしい

// 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": "スッキリわかるJava入門 実践編 第2版",
        "authors": [
          "中山清喬"
        ],
        "publisher": "(株)インプレス",
        "publishedDate": "2014-09-22",
        "description": "ラムダ式や日付APIなどJava8の注目機能の解説を増補し、アジャイル関連やデザインパターンについての解説も徹底強化した改訂版登場!姉妹書の『Java入門』と同じく「なぜ?」にしっかりと答えながら解説が進んでいきますので、正規表現やコレクション、データベース連携、リファクタリング、並列処理など、Javaを仕事で使いこなすために必須の知識が、スッキリ、楽しく、グングン身に付きます。基本文法やオブジェクト指向の概念はわかった、さらにステップアップしたい、という方にお勧めです。 発行",
        "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": "ラムダ式や日付APIなどJava8の注目機能の解説を増補し、アジャイル関連やデザインパターンについての解説も徹底強化した改訂版登場!姉妹書の『Java入門』と同じく「なぜ?」に ..."
      }
    }
  ]
}

JSONのモデルクラス(pojo)を生成

https://qiita.com/riversun/items/cdd990e96c2bbf9cb043
このページでjsonschema2pojoを使ってモデルクラス(pojo)を自動生成するを参考にしました

生成したクラスファイル

Screenshot from Gyazo

Modelクラスの中身です

Screenshot from Gyazo

@SerializeName("名前")
@Expose
public 型名 名前

itemsは "items": [ ]となっているので List< Item > items= null; になります

Screenshot from Gyazo

注意 

モデルクラスを自動生成しますが不足していることもありますので生成されていないものは自分で作ってください

javaメインコード

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コード
        Long isbn = 9784844336778L;

        //jsonを保持
        String json = "";

        OkHttpClient okHttpClient;

        okHttpClient = new OkHttpClient();

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

        //urlでリクエストを送信するアドレスを挿入
        builder.url(url + isbn);

        Request request = builder.build();

        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            //ここのjson上で上記したでweb api から帰ってきたjson情報を持っている
            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;

        //titleをmodelクラスから書いた場合
        //itemsクラスはList<Item>型なので.get()がつく
        System.out.println(models.items.get(0).volumeInfo.title);//title

        //モデルクラスをvolumeinfoクラスまで変更して表示した場合
        System.out.println("title: "    + volumeInfo.title);//title
        System.out.println("author: "   + volumeInfo.authors);//author
        System.out.println("出版日: "   + volumeInfo.publishedDate);//publishedDate
        System.out.println("出版社: "   + volumeInfo.publisher);//publisher
        System.out.println("定価:"      + listPrice.amount);
        System.out.println("説明:"     + volumeInfo.description);//description
        System.out.println("ページ数:" + volumeInfo.pageCount);//pageCount
        System.out.println("スモールサムネイル:" + imageLinks.smallThumbnail);//smallThumbnail
        System.out.println("サムネイル:"         + imageLinks.thumbnail);//thumbnail

    }
}

実行結果
Screenshot from Gyazo

という感じまで行けました

okhttpとjackson バージョンです

概要

java

mavenで

OkHttpはデフォルトで効率的なHTTPクライアント

okhttp バージョン 3.7.0使用
説明サイト
https://square.github.io/okhttp/

jackson 

jackson-core  バージョン:2.10.0
jackson-annotations バージョン:2.10.0
jackson-databind  バージョン:2.10.0

を入れています

  <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メインです

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 自動生成されたメソッド・スタブ
        Long isbn = 9784295007807L;

        //jsonを保持
        String json ="";

        //本の題名
        String title = "";
        //作者
        String author = "";
        //出版日
        Date publishedDate = null;
        String day = "";
        //出版社
        String publisher = "";
        //定価
        Integer listPrice = null;
        //説明文
        String description = "";
        //ページ数
        Integer pageCount = null;
        //smallサムネイル
        String smallThumbnail ="";
        //サムネイル
        String thumbnail = "";


        OkHttpClient okHttpClient;

        okHttpClient = new OkHttpClient();

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

        //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();
        }

        //jsonの内容を表示する
        System.out.println(json);

        //ここからjsonの中身を取り出して表示していく処理
        ObjectMapper mapper = new ObjectMapper();
        try {
            JsonNode node = mapper.readTree(json);

             //get("value")のvalueはjsonの"title": "スッキリわかるJava入門 実践編 第2版"
             //titleの部分がvalueになります
             //titleはString型なので末尾に .asText(); を付けます
             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();

             //出版日をDate型に変換するためにString dayで受け取り
             day = node.get("items").get(0).get("volumeInfo").get("publishedDate").textValue();

             //文字列をsql型のDateに変換
             publishedDate =  Date.valueOf(day);

             //listPriceは int型なので末尾に .asInt(); を付けます
             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("出版社: "+publisher);
        System.out.println("出版日: " + publishedDate);
        System.out.println("定価: " + listPrice + "円");
        System.out.println("説明文: " + description);
        System.out.println("ページ数: " + pageCount);
        System.out.println("小さいサムネイル: " + smallThumbnail);
        System.out.println("サムネイル: " +thumbnail);

    }

}

Screenshot from Gyazo

という風にできました

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2