JSON parsing in java from file

SirLacky :

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.

Mushif Ali Nawaz :

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());
            }
        }

    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=162777&siteId=1