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
Answer from Nowhere Man on Stack Overflow
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.

🌐
GitHub
github.com › HenrikPoulsen › SimpleJSON › issues › 4
How to check if JSONNode contains a key quickly? · Issue #4 · HenrikPoulsen/SimpleJSON
April 7, 2021 - public static bool ContainsKey(SimpleJSON.JSONNode node, string checkKey) { foreach (string key in node.Keys) { if (key == checkKey) return true; } return false; } }
Author   ROBYER1
🌐
Baeldung
baeldung.com › home › json › how to check if a value exists in a json array for a particular key
How to Check if a Value Exists in a JSON Array for a Particular Key | Baeldung
January 8, 2024 - After that, with our Stream ready, we inspected each JsonNode in turn. We needed to be slightly careful here. We have no confirmation that our input JSON has any keys called color. This could result in a NullPointerException when converting the value to a String for comparison. So first, we attempted to get the property, then filtered to remove any nulls that would occur if the JsonNode had no keys called color.
🌐
Fasterxml
fasterxml.github.io › jackson-databind › javadoc › 2.6 › com › fasterxml › jackson › databind › JsonNode.html
JsonNode (jackson-databind 2.6.0 API) - FasterXML
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) Method for finding a JSON Object field with specified name in this node or its child nodes, and returning value it has. If no matching field is found in this node or its descendants, returns null.
🌐
Red Hat
access.redhat.com › webassets › avalon › d › red-hat-jboss-enterprise-application-platform › 7.1.beta › javadocs › com › fasterxml › jackson › databind › JsonNode.html
JsonNode (Red Hat JBoss Enterprise Application Platform 7.1.0.Beta1 public API)
Method for accessing all value nodes of this Node, iff this node is a JSON Array or Object node. In case of Object node, field names (keys) are not included, only values. For other types of nodes, returns empty iterator. public Iterator<Map.Entry<String,JsonNode>> fields()
🌐
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 - While iterating using JsonParser, we can check the token type and perform required operations. Let’s fetch all the field names for our example JSON string: public List<String> getKeysInJsonUsingJsonParser(String json, ObjectMapper mapper) throws IOException { List<String> keys = new ArrayList<>(); JsonNode jsonNode = mapper.readTree(json); JsonParser jsonParser = jsonNode.traverse(); while (!jsonParser.isClosed()) { if (jsonParser.nextToken() == JsonToken.FIELD_NAME) { keys.add((jsonParser.getCurrentName())); } } return keys; } Here, we’ve used the traverse() method of the JsonNode class to get the JsonParser object.
Find elsewhere
🌐
SmartBear Community
community.smartbear.com › smartbear community › readyapi › readyapi questions
Require condition to check depending upon the Json Node response | SmartBear Community
Depending upon the json node, for a json node if the key exists and value exists i have to set property in custom properties and if the key value doesnt exist then i have to set the property with null value.
🌐
ArduinoJson
arduinojson.org › version 6 › api › jsonobject › containskey()
JsonObject::containsKey() | ArduinoJson 6
StaticJsonDocument<256> doc; doc["location"]["city"] = "Paris"; const char* city = doc["location"]["city"]; if (city) Serial.println(city); This version should lead to a smaller and faster code since it only does the lookup once. You cannot test the presence of nested keys with containsKey() but, as explained above, it’s safe to read the object anyway.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-check-if-a-key-exists-inside-a-json-object
Check if a key exists inside a JSON object - JavaScript - GeeksforGeeks
The message "city exists in the nested object." is logged. We can use JSON.stringify() to convert an object to a string and check if a key exists as a substring.
Published   July 11, 2025
🌐
Code Highlights
code-hl.com › home › javascript › tutorials
5 Quick Ways to Check If Key Exists in JSON Using JavaScript | Code Highlights
August 15, 2024 - This will confirm the existence of the name key. Sometimes, JSON objects are nested. To check for a key in a nested structure, you can use a function. ... This function splits the key string and checks each level of the object. You can also convert your JSON object to a string and check if it contains the key.
🌐
Jenkov
jenkov.com › tutorials › java-json › jackson-jsonnode.html
Jackson JsonNode
The at() method returns a JsonNode which represents the JSON field you requested. To get the actual value of the field you need to call one of the methods covered in the next section. If no node matches the given path expression, null will be returned.
🌐
Fasterxml
fasterxml.github.io › jackson-databind › javadoc › 2.4 › com › fasterxml › jackson › databind › JsonNode.html
JsonNode (jackson-databind 2.4.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) Method for finding a JSON Object field with specified name in this node or its child nodes, and returning value it has. If no matching field is found in this node or its descendants, returns null.
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java
Check Key-Value Pair Existence In JSON Array - Java Code Geeks
October 25, 2023 - package com.jcg.example; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class JsonArrayChecker { public static void main(String[] args) { // Sample JSON array as a string String jsonArray = "[{\"id\": 1, \"name\": \"John\"}, {\"id\": 2, \"name\": \"Alice\"}]"; // Key and value to search for String targetKey = "id"; int targetValue = 2; try { // Parse JSON array ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(jsonArray); // Check if the JSON array contains the specific key with the given value
Top answer
1 of 4
8

You can use JSONObject to parse your json and use its has(String key) method to check wether a key exists in this Json or not:

 String str="{\"claim_loss_type_cd\": \"TEL\",\"claim_type\":\"002\",\"claim_reason\": \"001\",\"policy_number\":\"1234kk3366ff664\",\"info\": {\"ApplicationContext\":{\"country\": \"US\"}}}";
 Object obj=JSONValue.parse(str);
 JSONObject json = (JSONObject) obj;
 //Then use has method to check if this key exists or not
 System.out.println(json.has("claim_type")); //Returns true

EDIT:

Or better you can simply check if the JSON String contains this key value, for example with indexOf() method:

String str="{\"claim_loss_type_cd\": \"TEL\",\"claim_type\":\"002\",\"claim_reason\": \"001\",\"policy_number\":\"1234kk3366ff664\",\"info\": {\"ApplicationContext\":{\"country\": \"US\"}}}";
System.out.println(str.indexOf("claim_type")>-1); //Returns true

EDIT 2:

Take a look at this method, it iterates over the nested objects to check if the key exists.

public boolean keyExists(JSONObject  object, String searchedKey) {
    boolean exists = object.has(searchedKey);
    if(!exists) {      
        Iterator<?> keys = object.keys();
        while( keys.hasNext() ) {
            String key = (String)keys.next();
            if ( object.get(key) instanceof JSONObject ) {
                    exists = keyExists(object.get(key), searchedKey);
            }
        }
    }
    return exists;
}

Object obj=JSONValue.parse(str);
JSONObject json = (JSONObject) obj;
System.out.println(keyExists(json, "country")); //Returns true
2 of 4
0

A ready-to-go method with correct casting of types:

/**
 * JSONObject contains the given key. Search is also done in nested 
 * objects recursively.
 *
 * @param json JSONObject to serach in.
 * @param key Key name to search for.
 * @return Key is found.
 */
public static boolean hasKey(
  JSONObject json,
  String key) {

  boolean exists = json.has(key);
  Iterator<?> keys;
  String nextKey;

  if (!exists) {

    keys = json.keys();

    while (keys.hasNext()) {
      nextKey = (String) keys.next();

      try {
        if (json.get(nextKey) instanceof JSONObject) {
          exists =
            hasKey(
              json.getJSONObject(nextKey),
              key);
        }
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
  }

  return exists;
}