我正在尝试使用openlibrary中的book API。 所以,我的问题是,我该如何抓取数据? 我需要刮标题,作者,出版者和出版日期。
JSON :
{
"ISBN:0789721813": {
"bib_key": "ISBN:0789721813",
"preview": "noview",
"preview_url": "https://openlibrary.org/books/OL18096553M/Red_Hat_Linux",
"info_url": "https://openlibrary.org/books/OL18096553M/Red_Hat_Linux",
"details": {
"number_of_pages": 757,
"subtitle": "installation and configuration handbook",
"latest_revision": 3,
"contributions": [
"Hellums, Duane"
],
"title": "Red Hat Linux",
"languages": [
{
"key": "/languages/eng"
}
],
"subjects": [
"Linux",
"Operating systems (Computers)"
],
"publish_country": "inu",
"by_statement": "Duane Hellums, et al",
"type": {
"key": "/type/edition"
},
"revision": 3,
"other_titles": [
"Red Hat Linux version 6.0"
],
"publishers": [
"Que"
],
"last_modified": {
"type": "/type/datetime",
"value": "2010-08-18T08:53:00.844526"
},
"key": "/books/OL18096553M",
"publish_places": [
"Indianapolis, Ind"
],
"pagination": "xix, 757 p. :",
"created": {
"type": "/type/datetime",
"value": "2008-10-10T19:27:28.086386"
},
"lccn": [
"99063852"
],
"notes": {
"type": "/type/text",
"value": "\"Red Hat Linux version 6.0.\"--Cover\n\nIncludes index"
},
"identifiers": {
"librarything": [
"261776"
],
"goodreads": [
"3382689"
]
},
"isbn_10": [
"0789721813"
],
"publish_date": "2000"
}
}
}
这是我的代码:
class JsonClass {
public static void main(String[] args) throws IOException {
org.jsoup.nodes.Document docKb = Jsoup
.connect("https://openlibrary.org/api/books?bibkeys=ISBN:0789721813&jscmd=details&format=json")
.ignoreContentType(true).get();
String json = docKb.body().text();
String titulo;
Container fullJsonObject = new Gson().fromJson(json, Container.class);
for (Details i : fullJsonObject.details) {
System.out.println("Author: " + i.by_statement);
System.out.println("Title: " + i.title);
System.out.println("Editora: " + i.type.publishers[0]);
System.out.println("Ano de publicação: " + i.type.notes);
}
}
private class Container {
Details[] details;
}
private class Details {
String title;
String by_statement;
Type type;
}
private class Type {
String publishers[];
Notes notes;
}
private class Notes {
String publish_date;
}
}
我尝试过,它只是在这一行上给了我一个java.lang.NullPointerException:
for (Details i : fullJsonObject.details) {
我很麻木,所以任何答案都可以帮上忙,
答案 0 :(得分:0)
您的问题是,您正在尝试解析一个具有Container
数组的Detail
,但是响应实际上是一个以Map
作为的Container.bib_key
键和Container
本身作为值,所以Map<String, Container>
。看来该API方法已准备好一次返回多个Container
也 Container.details
不是对象,而是单个值。因此,将Container
更改为:
private class Container {
Details details;
}
解析正确的对象可能会给您带来更好的结果,例如:
java.lang.reflect.Type type =
new TypeToken<Map<String, Container>>(){}.getType();
Map<String, Container> fullJsonObject = new Gson().fromJson(json, type);