java - 在java中获取JSON字符串JsonNode中的所有键

标签 java json jackson jsonnode

我有一个 json 字符串,我需要验证它并在 json 字符串中找到列表以外的任何其他键。示例 json 字符串是

{
    "required" : true,
    "requiredMsg" : "Title needed",
    "choices" : [ "a", "b", "c", "d" ],
    "choiceSettings" : {
        "a" : {
            "exc" : true
        },
        "b" : { },
        "c" : { },
        "d" : {
            "textbox" : {
                "required" : true
            }
        }
    },
    "Settings" : {
        "type" : "none"
    }
}

为了只允许预定义的键存在于 json 字符串中,我想获取 json 字符串中的所有键。如何获取 json 字符串中的所有键。我正在使用 jsonNode。到目前为止我的代码是

        JsonNode rootNode = mapper.readTree(option);
        JsonNode reqiredMessage = rootNode.path("reqiredMessage");             
        System.out.println("msg   : "+  reqiredMessage.asText());            
        JsonNode drNode = rootNode.path("choices");
        Iterator<JsonNode> itr = drNode.iterator();
        System.out.println("\nchoices:");
        while (itr.hasNext()) {
            JsonNode temp = itr.next();
            System.out.println(temp.asText());
        }    

如何使用JsonNode获取json字符串中的所有键值

最佳答案

forEach将遍历 JsonNode 的 child (打印时转换为 String)和 fieldNames()得到一个 Iterator<String>在 key 上。以下是打印示例 JSON 元素的一些示例:

JsonNode rootNode = mapper.readTree(option);

System.out.println("\nchoices:");
rootNode.path("choices").forEach(System.out::println);

System.out.println("\nAllKeys:");
rootNode.fieldNames().forEachRemaining(System.out::println);

System.out.println("\nChoiceSettings:");
rootNode.path("choiceSettings").fieldNames().forEachRemaining(System.out::println);

您可能需要 fields()在某些时候返回 Iterator<Entry<String, JsonNode>>这样您就可以遍历键值对。

关于java - 在java中获取JSON字符串JsonNode中的所有键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48785312/

相关文章:

java - 将命令行中的文本获取到 Java 中

php - MySQL 结果到 PHP 数组

c# - 如何使 JSON 文件成为 Visual Studio 2012 中项目的一部分

spring-mvc - Spring MVC : The request sent by the client was syntactically incorrect

java - 在 Java 中解析 JSON 数据 - 受 id 困扰

java - 使用线程管理 Sprite 动画

java - .NET ListBox 的 Swing 等价物

json - JSON 值是否可以包含多行字符串

java - 获取发送和接收 json 数据的路径变量 Rest spring mvc

java - Rapid Application Developer - "Publish"和 "Republish"之间的区别