java - 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.
解决方案
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.
推荐阅读
- vb.net - 在 VB.NET 中自动滚动到文本框的最后一行
- amazon-web-services - 断开连接:没有可用的受支持的身份验证方法(服务器发送:publickey)
- python - Turtle Graphics 完成后停止响应
- jquery - 无法从远程 ajax 请求中获取图像
- java - 我在查询中遇到错误
- ruby-on-rails - 验证失败时Rails嵌套对象消失
- javascript - 未找到 Jquery AJAX 404 form.php
- c++ - OpenGL 2d三角形围绕中心旋转
- html - 电子按钮有奇怪的造型
- node.js - 请在 docker npm test 中设置“CHROME_BIN”环境变量