检查 JSON 上是否存在字段
有时检查 JSON 上是否存在字段是有用的,以避免代码中存在某些字段。
要实现这一点,请使用 JSONObject#has(String)
或方法,如下例所示:
示例 JSON
{
"name":"James"
}
Java 代码
String jsonStr = " { \"name\":\"James\" }";
JSONObject json = new JSONObject(jsonStr);
// Check if the field "name" is present
String name, surname;
// This will be true, since the field "name" is present on our JSON.
if (json.has("name")) {
name = json.getString("name");
}
else {
name = "John";
}
// This will be false, since our JSON doesn't have the field "surname".
if (json.has("surname")) {
surname = json.getString("surname");
}
else {
surname = "Doe";
}
// Here name == "James" and surname == "Doe".