檢查 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".