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

就像:

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

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

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

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

jsonexception:没有club的值


当前回答

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

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(以)

其他回答

一个更好的方法,而不是使用条件句:

if (json.has("club")) {
    String club = json.getString("club"));
 }

就是简单地使用现有的方法optString(),就像这样:

String club = json.optString("club);

如果键不存在,optString("key")方法将返回空String,因此将抛出异常。

试试这个

if(!jsonObj.isNull("club")){
    jsonObj.getString("club");
}
I used hasOwnProperty('club')

var myobj = { "regatta_name":"ProbaRegatta",
    "country":"Congo",
    "status":"invited"
 };

 if ( myobj.hasOwnProperty("club"))
     // do something with club (will be false with above data)
     var data = myobj.club;
 if ( myobj.hasOwnProperty("status"))
     // do something with the status field. (will be true with above ..)
     var data = myobj.status;

适用于当前所有浏览器。

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

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(以)

试试这个:

let json=yourJson

if(json.hasOwnProperty(yourKey)){
    value=json[yourKey]
}