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 OverflowIf 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
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.
JSONObject class has a method named "has":
http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)
Returns true if this object has a mapping for name. The mapping may be NULL.
You can check this way where 'HAS' - Returns true if this object has a mapping for name. The mapping may be NULL.
if (json.has("status")) {
String status = json.getString("status"));
}
if (json.has("club")) {
String club = json.getString("club"));
}
You can also check using 'isNull' - Returns true if this object has no mapping for name or if it has a mapping whose value is NULL.
if (!json.isNull("club"))
String club = json.getString("club"));
To do a proper null check of a JsonNode field:
JsonNode jsonNode = response.get("item");
if(jsonNode == null || jsonNode.isNull()) { }
The item is either not present in response, or explicitly set to null .
OK, so if the node always exists, you can check for null using the .isNull() method.
if (!response.isNull("item")) {
// do some things with the item node
} else {
// do something else
}
Use below code to find key is exist or not in JsonObject. has("key") method is used to find keys in JsonObject.
containerObject = new JSONObject(container);
//has method
if (containerObject.has("video")) {
//get Value of video
String video = containerObject.optString("video");
}
If you are using optString("key") method to get String value then don't worry about keys are existing or not in the JsonObject.
Use:
if (containerObject.has("video")) {
//get value of video
}
You just get Response object from your call and do:
public class Test {
public static void main(String[] args) {
Response response = RestAssured
.get("https://mocki.io/v1/22617277-2eca-4fcf-b7e2-8c80851ef45d");
if(response.path("shop.type") == null){
System.out.println("key does not exist");
}else{
System.out.println(response.path("shop.type").toString());
}
}
}
You can have more complicated jsonpath query. For example if you treat having field with null value in different way than having no field at all you can use find in your jsonpath like I'm showing below:
if(response.path("shop.find{it.getKey() == 'type'}") != null){
System.out.print("Key exists ");
if(response.path("shop.type") == null){
System.out.println("but have null value");
}else{
System.out.println("and have not-null value");
}
}else{
System.out.println("Key does not exist");
}
Example json:
{
"priceOne": 1034,
"priceTwo": {"new":2},
"priceThree": 7282
}
Checking the value of "new"
Response response =RestAssured.get("https://newnnnnnnn.free.beeceptor.com").
then().extract().response();
JSONObject jsonObj = new JSONObject(response.asString());
String val = (jsonObj.getJSONObject("priceTwo").has("new")) ? response.jsonPath().getString("priceTwo.new"):"not foun";
System.out.println(val);
Try JSONObj.hetJsonobject
As mentioned in above comment you can use response.path("shop.type") == null ? true : false also . But shop.type returns null for non existence and also for {"type": null}
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
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;
}