I have a set of JSONObject
values which i receive from a server and operate on. Most times I get a JSONObject
with a value (let's say statistics) and sometimes, it returns an Error
object with a code and a description of the error.
How do I structure my code so that it doesn't break if it returns the error. I thought I could do this, but doesn't work.
public void processResult(JSONObject result) { try { if(result.getJSONObject(ERROR) != null ){ JSONObject error = result.getJSONObject(ERROR); String error_detail = error.getString(DESCRIPTION); if(!error_detail.equals(null)) { //show error login here } finish(); } else { JSONObject info = result.getJSONObject(STATISTICS); String stats = info.getString("production Stats")); } } }
To check null in JavaScript, use triple equals operator(===) or Object is() method. If you want to use Object.is() method then you two arguments. 1) Pass your variable value with a null value. 2) The null value itself.
Try with json. isNull( "field-name" ) . I would go further and say to NEVER use has(KEY_NAME), replacing those calls to ! isNull(KEY_NAME).
JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.
Using simple java rules. Check if the array is empty, if the array does not exist and you try to get it, it just returns null. Just handle it. Don't continue parsing if you know its going to fail.
Use .has(String)
and .isNull(String)
A conservative usage could be;
if (record.has("my_object_name") && !record.isNull("my_object_name")) { // Do something with object. }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With