Vishakha Kinjawadekar
Vishakha Kinjawadekar

Reputation: 51

how to check whether jsonobject contains boolean or null value?

I am working on json parser. In json response some values contains boolean or null values, then how to check whether it is boolean or null? For example : user = false or user = null . At the time of parsing it gives exception as "user is not jsonobject".

JSONObject json = new JSONObject(query);
JSONObject info = json.getJSONObject("info");
JSONObject user = info.getJSONObject("user");

Thanks, Vishakha.

Upvotes: 2

Views: 7011

Answers (4)

Ajit Kumar Dubey
Ajit Kumar Dubey

Reputation: 1563

JSONObject json = new JSONObject(data); 
String user = json.getString("user");
variable.setUser(courses_icon_file_name == null ? "": user);

Upvotes: 0

sajith
sajith

Reputation: 2702

isNull() you can use if(json.isNull("user")||your conditions)

Upvotes: 1

Giacomo
Giacomo

Reputation: 1

I think the problem might be that you are trying to get a JSONArray with getJSONObject(). try json.getJSONArray("info"). I had the same problem that i was trying to do if(object.getJSONObject("string") == null) but it threw an exception when trying to get the object to check for its value, and .optBoolean worked perfectly

Upvotes: 0

Erez A. Korn
Erez A. Korn

Reputation: 2758

Have you tried ingo.optBoolean("user")?

From the SDK documentation for optBoolean: Returns the value mapped by name if it exists and is a boolean or can be coerced to a boolean. Returns false otherwise.

Note that null will be treated as a false value in this example.

Upvotes: 2

Related Questions