Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if a JSONObject is null or doesn't exist

Tags:

java

json

android

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"));         }     } } 
like image 334
irobotxx Avatar asked Sep 25 '12 14:09

irobotxx


People also ask

How do you check if a JSON object is null or not?

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.

How check JSON object is null or not in android?

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

Does JSON use null or none?

JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.

How do you handle a null response in JSON?

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.


1 Answers

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.       } 
like image 109
BrantApps Avatar answered Sep 18 '22 13:09

BrantApps