ChanChow
ChanChow

Reputation: 1366

How to handle null response for json object

I get a JSON response as

{
"edges": [],
"nodes": []
}

how to check if the objects has null values and handle the case??

JSONObject jobj = new JSONObject(line);
JSONArray jArray = jobj.getJSONArray("edges");
if(jArray.length()!=0)
{    
  for(int i=0;i<jArray.length();i++){
  JSONObject json_data = jArray.getJSONObject(i);
  x.add((float) json_data.getInt("x"));
  y.add((float) json_data.getInt("y"));
end

This retrurns me : org.json.JSONException: end of input at character 0 of

Upvotes: 2

Views: 13876

Answers (4)

sachin003
sachin003

Reputation: 9053

try this on. I am showing example only for only one array depending on flag value you can show proper error message or on success you can bind parsed data to UI component.

String impuStr = "{\"edges\": [],\"nodes\": []}";

String flag = serverResponse(impuStr);

private String serverResponse(String jsonStr) { String flag = "success";

    JSONObject jobj;
    try {
        jobj = new JSONObject(jsonStr);

        JSONArray jArrayEdges = jobj.getJSONArray("edges");
        if(jArrayEdges != null && jArrayEdges.length() > 0)
        {    
          for(int i=0;i<jArrayEdges.length();i++)
          {
              JSONObject json_data = jArrayEdges.getJSONObject(i);
              // process data here
          }
         }else
             flag = "edges_list_empty";

    } catch (JSONException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
        flag = "failure";
    }

    return flag;
}

Upvotes: 2

fgeorgiew
fgeorgiew

Reputation: 1204

try this one:

String jsonString = "{ "edges": [], "nodes": [] }";

JSONObject jsonObject = new JSONObject(jsonString);

if( jsonObject.isNull("edges") == false) {
//do sth
}

if( jsonObject.isNull("nodes") == false) {
//do sth
}

you can also check if you have some particular key in your json by jsonObject.has("edges")

you are passing some \line\ variable to the JSONObject constructor. make sure that this variable contains your whole json string like this one in my example and not something like "{" or ' "edges": [] ' maybe the problem is in your json source like dokkaebi suggested in comment

Upvotes: 3

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132972

you can check as:

JSONObject jobj = new JSONObject(line);
if (jobj.getJSONArray("edges").length() == 0) {

    System.out.println("JSONArray is null");      
 }
 else{
      System.out.println("JSONArray is not null");
      //parse your string here         
     }

Upvotes: 2

jtt
jtt

Reputation: 13541

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. Just exist gracefully.

if (myObj != null)
{
  ... process
}

Upvotes: 0

Related Questions