我正在使用Spring上的Web API,它应该能够提供端点并基于从JSON文件读取的数据来提供相关信息。但是我在用Jackson反序列化嵌套JSON文件时遇到问题。
我创建了Book类,并尝试将JSON映射到HashMap以保留这些对象。 但是JSON文件具有比我想要的数据更多的数据,并且它像'volumeInfo'一样嵌套。
class Book {
private String isbn;
private String title;
private String subtitle;
private String publisher;
private long publishedDate;
private String description;
private int pageCount;
private String thumbnailUrl;
private String language;
private String previewLink;
private double averageRating;
private String[] authors;
private String[] categories;
// getters and setters
data.json文件示例
{
"requestedUrl": "https://www.googleapis.com/books/v1/volumes?q=java&maxResults=40",
"items": [
{
"kind": "books#volume",
"id": "7tkN1CYzn2cC",
"etag": "pfjjxSpetIM",
"selfLink": "https://www.googleapis.com/books/v1/volumes/7tkN1CYzn2cC",
"volumeInfo": {
"title": "A Hypervista of the Java Landscape",
"publisher": "InfoStrategist.com",
"industryIdentifiers": [
{
"type": "ISBN_13",
"identifier": "9781592432172"
},
{
"type": "ISBN_10",
"identifier": "1592432174"
}
],
]
}
我怎么能和Jackson一起获得那个volumeInfo?
答案 0 :(得分:2)
您需要将其解析为JsonNode
,遍历数组中的每个节点并转换为Book
:
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
JsonNode root = mapper.readTree(json); // read as JsonNode
JsonNode items = root.at("/items");
List<Book> books = new ArrayList<>();
if (items.isArray()) {
ArrayNode array = (ArrayNode) items;
array.forEach(n -> {
Book book = mapper.convertValue(n.get("volumeInfo"), Book.class); // convert to Book
books.add(book);
});
}
System.out.println(books);