我从服务器得到一些JSON值,但我不知道是否会有一个特定的字段。

就像:

{ "regatta_name":"ProbaRegatta",
  "country":"Congo",
  "status":"invited"
}

有时,会有一个额外的字段,比如:

{ "regatta_name":"ProbaRegatta",
  "country":"Congo",
  "status":"invited",
  "club":"somevalue"
}

我想检查名为“俱乐部”的字段是否存在,以便在解析时我不会得到

jsonexception:没有club的值


当前回答

你可以试着检查这个键是否存在:

JSONObject object = new JSONObject(jsonfile);
if (object.containskey("key")) {
  object.get("key");
  //etc. etc.
}

其他回答

在读取键之前检查一下,就像在读取之前一样

JSONObject json_obj=new JSONObject(yourjsonstr);
if(!json_obj.isNull("club"))
{
  //it's contain value to be read operation
}
else
{
  //it's not contain key club or isnull so do this operation here
}

isNull函数定义

Returns true if this object has no mapping for name or
if it has a mapping whose value is NULL. 

下面是isNull函数的官方文档链接

http://developer.android.com/reference/org/json/JSONObject.html isNull(以)

你可以jsonobject#有,提供键作为输入,并检查方法是否返回真或假。你也可以

使用optString代替getString:

如果存在则返回按名称映射的值,如果存在则强制返回 必要的。如果不存在这样的映射,则返回空字符串

我只是添加了另一个东西,如果你只是想检查是否在JSONObject中创建了任何东西,你可以使用长度(),因为默认情况下,当JSONObject被初始化时,没有键被插入,它只是有空括号{}和使用has(String key)没有任何意义。

所以你可以直接写if (jsonObject.length() > 0)和做你的事情。

学习快乐!

你可以用has

public boolean has(String key)

确定JSONObject是否包含特定的键。

例子

JSONObject JsonObj = new JSONObject(Your_API_STRING); //JSONObject is an unordered collection of name/value pairs

if (JsonObj.has("address")) { 
    //Checking address Key Present or not
    String get_address = JsonObj .getString("address"); // Present Key
}
else {
    //Do Your Staff
}

你可以使用jsonnode# hasNonNull(String fieldName),它混合了has方法和验证,如果它是一个空值或不是