[java] How to check if a json key exists?

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

This question is related to java android json

The answer is


Try this

if(!jsonObj.isNull("club")){
    jsonObj.getString("club");
}

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"));

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.
}

Try this:

let json=yourJson

if(json.hasOwnProperty(yourKey)){
    value=json[yourKey]
}

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
}

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.


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!


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


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
}

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


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)


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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?