• 11
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

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

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

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.
      }
  • 93
Reply Report

In JSONObject there is a 'Has' method that you can do to Determaine the key.

I have no idea if this will work but it looks Credible.

public void processResult(JSONObject result) {

    if(result.has("ERROR"))
    {
        JSONObject error = result.getJSONObject("ERROR")
        String error_detail = error.getString("DESCRIPTION");

        if(error_detail != null)
        {
            //Show Error Login
            finish();
        }
    }
    else if(result.has("STATISTICS"))
    {
        JSONObject info = result.getJSONObject("STATISTICS");
        String stats = info.getString("Production Stats");

        //Do something
    }
    else
    {
        throw new Exception("Could not parse JSON Object!");
    }
}
  • 10
Reply Report

It might be little late(it is for sure) but posting it for future readers

You can use JSONObject optJSONObject (String name) which will not throw any exception and

Returns the value mapped by name if it exists and is a JSONObject, or null otherwise.

so you can do

JSONObject obj = null;
if( (obj = result.optJSONObject("ERROR"))!=null ){
      // it's an error , now you can fetch the error object values from obj
}

or if you just want to test nullity without fetching the value then

if( result.optJSONObject("ERROR")!=null ){
    // error object found 
}

There is whole family of opt functions which either return null or you can also use the overloaded version to make them return any pre-defined values. e.g

String optString (String name, String fallback)

Returns the value mapped by name if it exists, coercing it if necessary, or fallback if no such mapping exists.

where coercing mean, it will try to convert the value into String type


A modified version of the @TheMonkeyMan answer to eliminate redundant look-ups

public void processResult(JSONObject result) {
    JSONObject obj = null;
    if( (obj = result.optJSONObject("ERROR"))!=null ){
       //^^^^ either assign null or jsonobject to obj
      //  if not null then  found error object  , execute if body                              
        String error_detail = obj.optString("DESCRIPTION","Something went wrong");
        //either show error message from server or default string as "Something went wrong"
        finish(); // kill the current activity 
    }
    else if( (obj = result.optJSONObject("STATISTICS"))!=null ){
        String stats = obj.optString("Production Stats");
        //Do something
    }
    else
    {
        throw new Exception("Could not parse JSON Object!");
    }
}
  • 8
Reply Report

It is sometimes more convenient and less ambiguous to have a NULL object than to use Java's null value.

  • JSONObject.NULL.equals(null) returns true.

    JSONObject.NULL.toString()returns "null".

Example:

System.out.println(test.get("address").equals(null)); // Preferred way System.out.println(test.getString("address").equals("null"));

source -- JSONObject oracle docs

  • 1
Reply Report