javajsonjacksonjsonnode

Get all the keys in a JSON string JsonNode in java


I have a json string which I need to validate and find any other keys other than in a list is there in the json string. The sample json string is

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

To allow only predifined keys is exsist in the json string I want to get all the keys in the json string. How can I obtain all the keys in the json string. I am using jsonNode. My code till now is

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

How to get all the keys from the json string using JsonNode


Solution

  • This should do it.

    Map<String, Object> treeMap = mapper.readValue(json, Map.class);
    
    List<String> keys  = Lists.newArrayList();
    List<String> result = findKeys(treeMap, keys);
    System.out.println(result);
    
    private List<String> findKeys(Map<String, Object> treeMap , List<String> keys) {
        treeMap.forEach((key, value) -> {
          if (value instanceof LinkedHashMap) {
            Map<String, Object> map = (LinkedHashMap) value;
            findKeys(map, keys);
          }
          keys.add(key);
        });
    
        return keys;
      }
    

    This will print out result as

    [required, requiredMsg, choices, exc, a, b, c, required, textbox, d, choiceSettings, type, Settings]