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

2023-11-26

我有一个 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());
        }    

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


forEach将迭代 a 的子级JsonNode(转换成String打印时)和fieldNames()得到一个Iterator<String>超过钥匙。以下是打印示例 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>>所以你可以迭代键、值对。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

java中获取JSON字符串JsonNode中的所有键 的相关文章

随机推荐