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

就像:

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

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

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

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

jsonexception:没有club的值


当前回答

试试这个

if(!jsonObj.isNull("club")){
    jsonObj.getString("club");
}

其他回答

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

你可以用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
}
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#有,提供键作为输入,并检查方法是否返回真或假。你也可以

使用optString代替getString:

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

JSONObject类有一个名为"has"的方法:

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

如果该对象有name的映射,则返回true。映射可能是NULL。