0

I want to put validation for check key is exist or not.

{
 "id":"ProbaRegatta",
 "name":"Congo",
 "email":"invited"
 }

And sometimes, there will be an extra field like:

  {
   "id":"ProbaRegatta",
   "name":"Congo",
   "email":"invited"
   "contact":"xxxx"
   }

so i would to check 'contact' key exist

W4R10CK
  • 5,502
  • 2
  • 19
  • 30
Divyesh Rudani
  • 231
  • 1
  • 2
  • 13

3 Answers3

1
JSONObject obj = new JSONObject(response.toString());
boolean check = obj.has("name");
Sohail Zahid
  • 8,099
  • 2
  • 25
  • 41
1

Take a look in below code

/**
 * Check the Existance of Given String in given JSONObject
 */

public static boolean hasData(JSONObject jsonObject, String string) {
    return jsonObject.has(string) && !jsonObject.isNull(string);
}`
W4R10CK
  • 5,502
  • 2
  • 19
  • 30
Tarun Dholakiya
  • 829
  • 1
  • 10
  • 16
1

Try this method jsonObject.has("key") for checking key is exit or not, and jsonObject.isNull("key") for null value.

W4R10CK
  • 5,502
  • 2
  • 19
  • 30
Shijil
  • 2,226
  • 18
  • 33