forEach will iterate over children of a JsonNode (converted to String when printed) and fieldNames() gets an Iterator<String> over keys. Here are some examples for printing elements of the example 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);

You'll probably need fields() at some point that returns an Iterator<Entry<String, JsonNode>> so you can iterate over key, value pairs.

Answer from Manos Nikolaidis on Stack Overflow
🌐
Baeldung
baeldung.com › home › json › jackson › get all the keys in a json string using jsonnode
Get all the Keys in a JSON String Using JsonNode | Baeldung
May 11, 2024 - Now let’s discuss different approaches to fetch keys from a JSON. We can use the fieldNames() method on a JsonNode instance to fetch the nested field names. It returns names of direct nested fields only.
🌐
Tabnine
tabnine.com › home page › code › java › org.codehaus.jackson.jsonnode
org.codehaus.jackson.JsonNode.getFields java code examples | Tabnine
protected static void fromJson( String value, Set<String> fields, Map<String, ByteIterator> result) throws IOException { JsonNode json = MAPPER.readTree(value); boolean checkFields = fields != null && !fields.isEmpty(); for (Iterator<Map.Entry<String, JsonNode>> jsonFields = json.getFields(); jsonFields.hasNext(); /* increment in loop body */) { Map.Entry<String, JsonNode> jsonField = jsonFields.next(); String name = jsonField.getKey(); if (checkFields && !fields.contains(name)) { continue; } JsonNode jsonValue = jsonField.getValue(); if (jsonValue != null && !jsonValue.isNull()) { result.put(
Top answer
1 of 2
2

You can use elements() method and check if value key exist then add the value to list.

Smaple code

ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(data);

List<String> values = new ArrayList<>();
jsonNode.forEach(jsonObject -> jsonObject.elements().forEachRemaining(valueNode -> {
    if(valueNode.has("value"))
        values.add(valueNode.get("value").asText());
}));
System.out.println(values);

Output:

[http://www.wikidata.org/entity/Q42442324, http://www.wikidata.org/prop/direct/P21, Kiisu Miisu, http://www.wikidata.org/entity/Q43260736, http://www.wikidata.org/prop/direct/P21, Paddles]
2 of 2
0

Here is the solution by "Josson & Jossons". I list 2 more examples with condition filtering.

https://github.com/octomix/josson

implementation 'com.octomix.josson:josson:1.3.22'

---------------------------------------------

Josson josson = Josson.fromJsonString(
    "[" +
    "  {" +
    "    \"item\": {" +
    "      \"type\": \"uri\", \"value\": \"http://www.wikidata.org/entity/Q42442324\"" +
    "    }," +
    "    \"prop\": {" +
    "      \"type\": \"uri\", \"value\": \"http://www.wikidata.org/prop/direct/P21\"" +
    "    }," +
    "    \"itemLabel\": {" +
    "      \"xml:lang\": \"en\", \"type\": \"literal\", \"value\": \"Kiisu Miisu\"" +
    "    }" +
    "  }," +
    "  {" +
    "    \"item\": {" +
    "      \"type\": \"uri\", \"value\": \"http://www.wikidata.org/entity/Q43260736\"" +
    "    }," +
    "    \"prop\": {" +
    "      \"type\": \"uri\", \"value\": \"http://www.wikidata.org/prop/direct/P21\"" +
    "    }," +
    "    \"itemLabel\": {" +
    "      \"xml:lang\": \"en\", \"type\": \"literal\", \"value\": \"Paddles\"" +
    "    }" +
    "  }" +
    "]");

JsonNode node = josson.getNode("*.value");
System.out.println("1.\n" + node.toPrettyString());

node = josson.getNode("~'^item.*'.value");
System.out.println("2.\n" + node.toPrettyString());

node = josson.getNode("*[value.type='uri']*.value");
System.out.println("3.\n" + node.toPrettyString());

Output:

1.
[ "http://www.wikidata.org/entity/Q42442324", "http://www.wikidata.org/prop/direct/P21", "Kiisu Miisu", "http://www.wikidata.org/entity/Q43260736", "http://www.wikidata.org/prop/direct/P21", "Paddles" ]
2.
[ "http://www.wikidata.org/entity/Q42442324", "Kiisu Miisu", "http://www.wikidata.org/entity/Q43260736", "Paddles" ]
3.
[ "http://www.wikidata.org/entity/Q42442324", "http://www.wikidata.org/prop/direct/P21", "http://www.wikidata.org/entity/Q43260736", "http://www.wikidata.org/prop/direct/P21" ]
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › system.text.json.nodes.jsonobject.system-collections-generic-idictionary-system-string-system-text-json-nodes-jsonnode--keys
JsonObject.IDictionary<String,JsonNode>.Keys Property (System.Text.Json.Nodes) | Microsoft Learn
Gets a collection containing the property names in the JsonObject. property System::Collections::Generic::ICollection<System::String ^> ^ System::Collections::Generic::IDictionary<System::String,System::Text::Json::Nodes::JsonNode>::Keys { ...
🌐
Adobe Experience League
experienceleaguecommunities.adobe.com › t5 › adobe-experience-manager › extract-keys-from-json-node › m-p › 209101
Solved: Extract keys from Json Node - Adobe Experience League Community - 209101
February 16, 2016 - Out of this, I need to fetch keys which contains values inside { }. Like, in this case, rwdcarousel · String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}"; JSONObject jObject = new JSONObject(s); JSONObject menu = jObject.getJSONObject("menu"); · Map<String,String> map = ...
Find elsewhere
🌐
Jenkov
jenkov.com › tutorials › java-json › jackson-jsonnode.html
Jackson JsonNode
As you can see in the JSON string in the example, the f2 field is declared, but set to null. In that case, the call jsonNode.get("f2").asText("Default") will return the default value, which in this example is the string Default.
🌐
Sourceforge
weka.sourceforge.io › doc.dev › weka › core › json › JSONNode.html
JSONNode
public JSONNode.NodeType getNodeType() Returns the type of the container. Returns: the type · public JSONNode addNull(java.lang.String name) Adds a "null" child to the object. Parameters: name - the name of the null value · Returns: the new node, or null if none added · public JSONNode addPrimitive(java.lang.String name, java.lang.Boolean value) Adds a key-value child to the object.
🌐
Makeseleniumeasy
makeseleniumeasy.com › 2020 › 09 › 01 › rest-assured-tutorial-44-fetch-value-from-json-object-using-jsonnode-jackson
REST Assured Tutorial 44 – Fetch Value From JSON Object Using JsonNode – Jackson – get() & path() Methods
As per the official doc – path() method is similar to get(String), except that instead of returning null if no such value exists (due to this node not being an object, or object not having value for the specified field), a “missing node” will be returned. This allows for convenient and safe chained access via path calls. // Retrieving value of non-existing key String s = jsonTree.get("nonExistingNode").asText("Default Value"); System.out.println(s);
🌐
Makeseleniumeasy
makeseleniumeasy.com › 2020 › 08 › 22 › rest-assured-tutorial-43-get-all-keys-from-a-nested-json-object
REST Assured Tutorial 43 – Get All Keys From A Nested JSON Object
August 22, 2020 - package JacksonTutorials; import java.util.Iterator; import org.testng.annotations.Test; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class GetAllKeysFromJsonObject { @Test public void getAllKeysFromJsonObjectUsingObjectMapper() throws JsonMappingException, JsonProcessingException { String jsonObject = "{\r\n" + " \"firstName\": \"Animesh\",\r\n" + " \"lastName\": \"Prashant\"\r\n" + "}"; ObjectMapper objectMapper = new ObjectMapper(); // Converting JSON Object string to JsonNode JsonNode parsedJsonObject = objectMapper.readTree(jsonObject); // Get all fields or keys Iterator allKeys= parsedJsonObject.fieldNames(); System.out.println("All keys are : "); allKeys.forEachRemaining(k -> System.out.println(k)); } }
🌐
Fasterxml
fasterxml.github.io › jackson-databind › javadoc › 2.7 › com › fasterxml › jackson › databind › JsonNode.html
JsonNode (jackson-databind 2.7.0 API)
Iterator that can be used to traverse all key/value pairs for object nodes; empty iterator (no contents) for other types · public abstract JsonNode findValue(String fieldName)
Top answer
1 of 2
12

If you're trying to find a key which is placed inside nested object, you may use findValue(String key) method which returns null if a value is not found by the given key:

ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode= mapper.readTree(json);

String[] keys = {
    "id", "create_date", "versions_control_advanced", "name", "nofield"
};

for (String key : keys) {
    JsonNode value = rootNode.findValue(key);
    System.out.printf("Key %s exists? %s --> value=%s%n", key, value != null,
                    value == null ? null : value.asText());

}

Output:

Key id exists? true --> value=276625
Key create_date exists? true --> value=2020-06-22T16:19:07
Key versions_control_advanced exists? true --> value=false
Key name exists? true --> value=
Key nofield exists? false --> value=null
2 of 2
0

I think you are not bound to the has() method.

You can convert the json to a map and then find the node recursively

    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.readValue( body, Map.class );

    ArrayList<Object> container = new ArrayList<>();
    boolean value = find( map, "id", container );

    if( value )
    {
        System.out.println( container );
    }

The recursive method should visit all the nodes and return soon as node is found

private static boolean find( Map<String, Object> map, String search, ArrayList<Object> container )
    {
        int i = 0;
        for( String s : map.keySet() )
        {
            i++;
            if( s.equals( search ) )
            {
                container.add( map.get( s ) );
                return true;
            }
            if( map.get( s ) instanceof Map )
            {
                boolean found = find( (Map<String, Object>) map.get( s ), search, container );
                if( i == map.size() || found )
                {
                    return found;
                }
            }
        }
        return false;
    }

I have edited the code to get the value also. hope this helps. I strongly suggest you to do more research on yourself before looking for help from the community.

🌐
Baeldung
baeldung.com › home › json › jackson › working with tree model nodes in jackson
Working with Tree Model Nodes in Jackson | Baeldung
January 8, 2024 - Instead, we’ll use JsonNode.fields because this gives us access to both the field name and value: Key="name", Value=Object {"first": "Tatu", "last": "Saloranta"} Key="title", Value=Value "Jackson Founder" Key="company", Value=Value "FasterXML" Key="pets", Value=Array [{"type": "dog", "number": 1},{"type": "fish", "number": 50}]
🌐
Java Code Geeks
javacodegeeks.com › home › enterprise java
Find Nested Key via Jackson Example - Java Code Geeks
October 8, 2024 - Line 9: this method will find the nested key based on the given paths. Line 18, 28: utilize the findValue method to find the field from JSON. Line 21: when the field is not found, findValue returns null. In this step, I will create a FindNodeByPath.java that finds a nested node via Jackson JsonNode.path method.