繁体   English   中英

从文件在java中解析JSON

[英]JSON parsing in java from file

我正在做 JSON 编程的第一步。 我有带有书籍存档的大 json 文件:

https://www.googleapis.com/books/v1/volumes?q=java&maxResults=30

我用 getter 和 setter 创建了 POJO。 现在我想找到例如给定作者写的所有书籍:

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

但可悲的是,我做错了什么。 我的应用程序只写了整个 json。

您需要访问内部节点以比较作者值。 您可能想要这样做:

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

    }
}

大多数jsonNode方法期望fieldNames不是实际值。

如果您正在寻找ISBN,则可以这样做(因此这可能不是最好的例子)

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

谢谢大家,这正是我所需要的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM