我从服务器得到一些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(以)

其他回答

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

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

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

Json有一个名为containsKey()的方法。

你可以使用它来检查某个键是否包含在Json集中。

File jsonInputFile = new File("jsonFile.json"); 
InputStream is = new FileInputStream(jsonInputFile);
JsonReader reader = Json.createReader(is);
JsonObject frameObj = reader.readObject();
reader.close();

if frameObj.containsKey("person") {
      //Do stuff
}

试试这个

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

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

试试这个:

let json=yourJson

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