Segue a minha resolução do exercício do GoogleBooksAPI, agradeço ao https://cursos.alura.com.br/user/rafaelboldrini pela ajuda quando precisei modelar a estrutura JSON recebida.
Classe Record Livro:
public record Livro(String title, String[] authors, String publisher, String publishedDate) {
}
Classe JsonTreatment:
public class JsonTreatment {
private Item[] items;
public Item[] getItems() {
return items;
}
public static class Item {
private VolumeInfo volumeInfo;
public VolumeInfo getVolumeInfo() {
return volumeInfo;
}
}
public static class VolumeInfo {
private String title;
private String[] authors;
private String publisher;
private String publishedDate;
public String getTitle() {
return title;
}
public String[] getAuthors() {
return authors;
}
public String getPublisher() {
return publisher;
}
public String getPublishedDate() {
return publishedDate;
}
}
}
Classe da API:
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Scanner;
public class PesquisaLivros {
public static void main(String[] args) throws IOException, InterruptedException {
Scanner scanner = new Scanner(System.in);
System.out.println("Insira o nome do resposta que você deseja buscar:");
var resposta = scanner.nextLine();
String API_KEY = "***************************************";
String adress = "https://www.googleapis.com/books/v1/volumes?q=" + resposta + "&fields=items&key=" + API_KEY;
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(adress))
.build();
HttpResponse<String> response = client
.send(request, HttpResponse.BodyHandlers.ofString());
String json = response.body();
Gson gson = new GsonBuilder().create();
JsonTreatment respostaLivros = gson.fromJson(json, JsonTreatment.class);
if (respostaLivros.getItems().length > 0) {
JsonTreatment.VolumeInfo volumeInfo = respostaLivros.getItems()[0].getVolumeInfo();
Livro livro = new Livro(volumeInfo.getTitle(), volumeInfo.getAuthors(), volumeInfo.getPublisher(), volumeInfo.getPublishedDate());
System.out.println(livro);
} else {
System.out.println("Nenhum livro encontrado.");
}
}
}