Java | Check if JSON field has a value before extracting

|
| By Webner

We are using Json to retrieve value of a field from Json object but when field has no value it gives an error. For example from Blackboard LMS we can retrieve value of email field from JSON object with this code:

first.getJSONObject(i).getJSONObject("contact").getString("email"))

And if we have to set this in user object, we can have this code statement:

user.setEmail(first.getJSONObject(i).getJSONObject("contact").getString("email"));

Now if getString(“email”) has no value above statement will give an error. So firstly we need to check if value exists or not. We can do it like this:

if(first.getJSONObject(i).has("contact") && first.getJSONObject(i).getJSONObject("contact").has("email"))
{	    		    user.setEmail(first.getJSONObject(i).getJSONObject("contact").getString("email"));
}

Webner Solutions is a Software Development company focused on developing CRM apps (Salesforce, Zoho), LMS Apps (Moodle/Totara), Websites and Mobile apps. If you need Web development or any other software development assistance please contact us at webdevelopment@webners.com

Leave a Reply

Your email address will not be published. Required fields are marked *