217

So, I get some JSON values from the server but I don't know if there will be a particular field or not.

So like:

{ "regatta_name":"ProbaRegatta",
  "country":"Congo",
  "status":"invited"
}

And sometimes, there will be an extra field like:

{ "regatta_name":"ProbaRegatta",
  "country":"Congo",
  "status":"invited",
  "club":"somevalue"
}

I would like to check if the field named "club" exists so that at parsing I won't get

org.json.JSONException: No value for club

Syscall
  • 19,327
  • 10
  • 37
  • 52
Adam Varhegyi
  • 11,307
  • 33
  • 124
  • 222

13 Answers13

337

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.

PX Developer
  • 8,065
  • 7
  • 42
  • 66
  • What if the key is from `Integer` type? – Eido95 May 15 '17 at 19:33
  • 2
    @Eido95 having an `Integer` as a key sounds like bad practice. JSON should be with a String key and a value of whatever you need. – Nico Jul 24 '17 at 11:11
  • @Eido95, I believe for an integer there is always a value, every time you declare an integer, you have to initialize it with a value. – mut tony Feb 09 '18 at 18:54
180

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"));
Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98
Nirali
  • 13,571
  • 6
  • 40
  • 53
19

you could JSONObject#has, providing the key as input and check if the method returns true or false. You could also

use optString instead of getString:

Returns the value mapped by name if it exists, coercing it if necessary. Returns the empty string if no such mapping exists

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
  • 1
    Although this method of may be of use for others, this does not return if the value exists. If `getString` would have returned an empty string, `optString` would also return an empty string. Assumption would then have you believe that the property isn't available in OP's situation. – halfpastfour.am Aug 16 '14 at 18:56
  • @Blackbelt do you have sources for this? – Taku Oct 06 '16 at 18:37
18

just before read key check it like before read

JSONObject json_obj=new JSONObject(yourjsonstr);
if(!json_obj.isNull("club"))
{
  //it's contain value to be read operation
}
else
{
  //it's not contain key club or isnull so do this operation here
}

isNull function definition

Returns true if this object has no mapping for name or
if it has a mapping whose value is NULL. 

official documentation below link for isNull function

http://developer.android.com/reference/org/json/JSONObject.html#isNull(java.lang.String)

SSpoke
  • 5,656
  • 10
  • 72
  • 124
Stack Overflow User
  • 4,052
  • 6
  • 29
  • 47
10

You can use has

public boolean has(String key)

Determine if the JSONObject contains a specific key.

Example

JSONObject JsonObj = new JSONObject(Your_API_STRING); //JSONObject is an unordered collection of name/value pairs

if (JsonObj.has("address")) { 
    //Checking address Key Present or not
    String get_address = JsonObj .getString("address"); // Present Key
}
else {
    //Do Your Staff
}
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
7

A better way, instead of using a conditional like:

if (json.has("club")) {
    String club = json.getString("club"));
 }

is to simply use the existing method optString(), like this:

String club = json.optString("club);

the optString("key") method will return an empty String if the key does not exist and won't, therefore, throw you an exception.

fuzzKitty
  • 334
  • 3
  • 7
3

Try this:

let json=yourJson

if(json.hasOwnProperty(yourKey)){
    value=json[yourKey]
}
Aishwarya
  • 987
  • 3
  • 10
  • 26
3

Json has a method called containsKey().

You can use it to check if a certain key is contained in the Json set.

File jsonInputFile = new File("jsonFile.json"); 
InputStream is = new FileInputStream(jsonInputFile);
JsonReader reader = Json.createReader(is);
JsonObject frameObj = reader.readObject();
reader.close();

if frameObj.containsKey("person") {
      //Do stuff
}
Christoph Grimmer
  • 4,210
  • 4
  • 40
  • 64
1

Try this

if(!jsonObj.isNull("club")){
    jsonObj.getString("club");
}
R9J
  • 6,605
  • 4
  • 19
  • 25
  • 3
    `isNull` is actually for to check if mapping is null, not for checking availability of a json member. – Reza_Rg Jul 22 '15 at 05:09
1
I used hasOwnProperty('club')

var myobj = { "regatta_name":"ProbaRegatta",
    "country":"Congo",
    "status":"invited"
 };

 if ( myobj.hasOwnProperty("club"))
     // do something with club (will be false with above data)
     var data = myobj.club;
 if ( myobj.hasOwnProperty("status"))
     // do something with the status field. (will be true with above ..)
     var data = myobj.status;

works in all current browsers.

cdturner
  • 392
  • 3
  • 11
1

You can try this to check wether the key exists or not:

JSONObject object = new JSONObject(jsonfile);
if (object.containskey("key")) {
  object.get("key");
  //etc. etc.
}
Dorus Blanken
  • 13
  • 1
  • 9
0

I am just adding another thing, In case you just want to check whether anything is created in JSONObject or not you can use length(), because by default when JSONObject is initialized and no key is inserted, it just has empty braces {} and using has(String key) doesn't make any sense.

So you can directly write if (jsonObject.length() > 0) and do your things.

Happy learning!

Gurinder
  • 943
  • 2
  • 9
  • 19
0

You can use the JsonNode#hasNonNull(String fieldName), it mix the has method and the verification if it is a null value or not