0

I'm using Json Path library and I want to check if key exists or not and based on that I'll do some actions. Hence I wrote following code -

for(int i = 0; i < keyValues.length; i++) {
  List<String> invalidKeys = new ArrayList<>();

  if(Objects.isNull(jsonPath.getString(key))) {
     invalidKeys.add(key);
     continue;
  }else {
     value = keyValues[i].split("=")[1];
  }
}

My intention to get keys which are not present in json but with this code, if key has value as null that is also treated non-existing key. Is there any way I can modify above code to get only keys which are not present in json?

tom redfern
  • 30,562
  • 14
  • 91
  • 126
Alpha
  • 13,320
  • 27
  • 96
  • 163

1 Answers1

0

You can use your jsonPath to build a JSONObject:

JSONObject jsonObject = new JSONObject(jsonPath.prettify());

Then you can use this jsonObject to check if the key exists:

for(int i = 0; i < keyValues.length; i++) {
  List<String> invalidKeys = new ArrayList<>();

  if(!jsonObject.has(key)) {
     invalidKeys.add(key);
     continue;
  }else {
     value = keyValues[i].split("=")[1];
  }
}