I am doing my first steps with JSON programming. I have big json file with books archive from:
https://www.googleapis.com/books/v1/volumes?q=java&maxResults=30
I created POJO's with getters and setters. Now I want to find for example all books wrote by given author:
byte[] jsonData = Files.readAllBytes(Paths.get("archive.json"));
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(jsonData);
JsonNode authorNode = rootNode.path("Gary Cornell");
Iterator<JsonNode> elements = authorNode.elements();
while(elements.hasNext()){
JsonNode isbn = elements.next();
System.out.println(isbn.textValue());
}
But saddly I am doing something wrong. My app just write whole json.
You need to access inner nodes to compare author values. You might want to do it like this:
byte[] jsonData = Files.readAllBytes(Paths.get("volumes.json"));
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(jsonData);
String authorName = "Joshua Bloch"; // author name to find
JsonNode items = rootNode.path("items");
Iterator<JsonNode> elements = items.elements();
while(elements.hasNext()){
JsonNode isbn = elements.next();
if(isbn.has("volumeInfo")) {
JsonNode volumeInfo = isbn.path("volumeInfo");
if(volumeInfo.has("authors")) {
JsonNode authors = volumeInfo.path("authors");
if(authors.toString().contains(authorName)) {
// Print complete book JSON value
System.out.println(isbn.toString());
}
}
}
}
Most of the jsonNode methods expect fieldNames not actual values.
If you`re looking for the ISBN you can do it like this (so this is probably not the best example)
public static void main(String[] args) throws IOException {
byte[] jsonData = Files.readAllBytes(Paths.get("archive.json"));
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(jsonData);
List<JsonNode> volumeNodes = rootNode.findValues("volumeInfo");
String authorName = "Gary Cornell";
for (JsonNode volumeNode : volumeNodes) {
JsonNode authors = volumeNode.path("authors");
Iterator<JsonNode> authorIt = authors.elements();
while(authorIt.hasNext()){
JsonNode author = authorIt.next();
if (authorName.equals(author.textValue())) {
System.out.println(author.textValue());
JsonNode isbn = volumeNode.path("industryIdentifiers");
Iterator<JsonNode> isbnIt = isbn.elements();
while(isbnIt.hasNext()) {
System.out.println(isbnIt.next());
}
}
}
}
}
谢谢大家,这正是我所需要的。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.