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 - If yes, we’ll traverse the value object as well to fetch inner nodes. As a result, we’ll get all the key names present in JSON: [Name, Age, BookInterests, Book, Author, Book, Author, FoodInterests, Breakfast, Bread, Beverage, Sandwich, Beverage] In the above example, we can also use the fields() method of the JsonNode class to get field objects instead of just field names:
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" ]
🌐
Tabnine
tabnine.com › home page › code › java › org.codehaus.jackson.jsonnode
org.codehaus.jackson.JsonNode.getFields java code examples | Tabnine
private Map<String, Set<String>> extractTextProperties(JsonNode node) { Map<String, Set<String>> resultMap = new HashMap<String, Set<String>>(); // get an iterator to the fields Iterator<Entry<String, JsonNode>> nodeIterator = node.getFields(); while ( nodeIterator.hasNext() ) { Entry<String, JsonNode> oneEntry = nodeIterator.next(); String key = oneEntry.getKey(); Set<String> valueSet = new HashSet<String>(); JsonNode valueNodes = oneEntry.getValue(); if ( valueNodes != null ) { for ( JsonNode oneValue : valueNodes ) { if ( oneValue != null ) { valueSet.add( extractTextNode( oneValue ) ); } } } resultMap.put( key, valueSet ); } return resultMap; }
🌐
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
Numbers are coerced using default Java rules; booleans convert to 0 (false) and 1 (true), and Strings are parsed using default Java language integer parsing rules. If representation cannot be converted to an long (including structured types like Objects and Arrays), default value of 0 will be returned; no exceptions are thrown. When you are trying to retrieve a value method for a node that doesn’t exist using get() then you will get NullPointerException. // Retrieving value of non-existing key System.out.println(jsonTree.get("nonExistingNode").asText());
🌐
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 - You can see this while debugging else if(value instanceof LinkedHashMap ) { @SuppressWarnings("unchecked") Set allKeysOfNestedJsonObject = ((LinkedHashMap)value).keySet(); allKeysOfNestedJsonObject.stream().forEach(k->System.out.println(k)); } }); } } ... 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; import com.fasterxml.jackson.databin
🌐
Sourceforge
weka.sourceforge.io › doc.dev › weka › core › json › JSONNode.html
JSONNode
public JSONNode addPrimitive(java.lang.String name, java.lang.Boolean value) Adds a key-value child to the object. Parameters: name - the name of the pair · value - the value · Returns: the new node, or null if none added · public JSONNode addPrimitive(java.lang.String name, java.lang.Integer ...
🌐
TutorialsPoint
tutorialspoint.com › how-to-access-the-json-fields-arrays-and-nested-objects-of-jsonnode-in-java
How to access the JSON fields, arrays and nested objects of JsonNode in Java?
May 13, 2025 - We can access a field, array or nested object using the get() method of the JsonNode class. We can return a valid string representation using the asText() method and convert the value of the node to a Java int using the asInt() method of JsonNode class.
🌐
CodingTechRoom
codingtechroom.com › tutorial › java-how-to-use-jsonnode-to-retrieve-keys-in-java
CodingTechRoom - How to Use JsonNode to Retrieve Keys in Java
Now that we have our JSON data parsed into a JsonNode, we can retrieve specific keys from it. Let's demonstrate how to do that with some code examples. ... import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.io.IOException; public class JsonNodeExample { public static void main(String[] args) { ObjectMapper objectMapper = new ObjectMapper(); try { JsonNode jsonNode = objectMapper.readTree(new File("data.json")); // Retrieving values using keys int userId = jsonNode.path("user").path("id").asInt(); String userName = jsonNode.path("user").path("name").asText(); String userEmail = jsonNode.path("user").path("email").asText(); System.out.println("User ID: " + userId); System.out.println("User Name: " + userName); System.out.println("User Email: " + userEmail); } catch (IOException e) { e.printStackTrace(); } } }
Find elsewhere
🌐
CodingTechRoom
codingtechroom.com › tutorial › java-java-jsonnode-get-keys
Java JsonNode: How to Get Keys with Examples - CodingTechRoom
Once we have our `JsonNode`, we can easily access the keys using the `fields()` method, which returns an iterator of the fields contained within the node.
🌐
Jenkov
jenkov.com › tutorials › java-json › jackson-jsonnode.html
Jackson JsonNode
Notice the parameter passed to the at() method: The string /identification/name . This is a JSON path expression. This path expression specifies the complete path from the root JsonNode and down to the field you want to access the value of.
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.

🌐
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)
🌐
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 - var json = $.parseJSON(data); var keys = $.map(json[16].events.burstevents,function(v,k) { return k; }); You can use JavaScript Object · var json = $.parseJSON(data); var keys = Object.keys(json[16].events.burstevents); ... String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}"; JSONObject jObject = new JSONObject(s); JSONObject menu = jObject.getJSONObject("menu"); Map<String,String> map = new HashMap<String,String>(); Iterator iter = menu.keys(); while(iter.hasNext()){ String key = (String)iter.next(); String value = menu.getString(key); map.put(key,value); }
🌐
Stack Overflow
stackoverflow.com › questions › 66024879 › how-to-access-the-value-from-a-key-value-pair-in-a-jsonnode
java - How to access the value from a key-value pair in a jsonnode - Stack Overflow
public void getColorCode() throws JsonProcessingException { String color = "{\"Pink\":[\"#000000\"],\"Red\":[\"#000000\"],\"Blue\":[\"#000000\"],\"Orange\":[\"#000000\"]}"; ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(color); for (JsonNode colorCode : node.get("Pink")){ System.out.println(colorCode); } } ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... Live from re:Invent…it’s Stack Overflow! The 2025 Stack Overflow and Stack Exchange wrap—our top ten questions of the...