如何处理json对象的null响应

时间:2012-12-05 19:50:47

标签: android json

我得到了一个JSON响应

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

如何检查对象是否具有空值并处理大小写?

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

这让我反感:org.json.JSONException:

字符0的输入结束

4 个答案:

答案 0 :(得分:3)

试试这个:

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

JSONObject jsonObject = new JSONObject(jsonString);

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

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

你也可以通过jsonObject.has(“edges”)检查你的json中是否有一些特定的键

您正在将一些\ line \ variable传递给JSONObject构造函数。确保这个变量在我的例子中包含你的整个json字符串,而不是像  “{”或“”edge“:[]'可能问题出现在你的json源代码中,如dokkaebi在评论中提出

答案 1 :(得分:2)

你可以检查:

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         
     }

答案 2 :(得分:2)

尝试此操作。我只显示一个数组的示例,具体取决于标志值,您可以显示正确的错误消息,或者成功时您可以将解析后的数据绑定到UI组件。

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

答案 3 :(得分:0)

使用简单的java规则。检查数组是否为空,如果数组不存在并且您尝试获取它,它只返回null。只是处理它。如果你知道它会失败,请不要继续解析。只是优雅地存在。

if (myObj != null)
{
  ... process
}
相关问题