共計 630 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,你可以使用 JSONObject 的 has
方法來判斷一個 JSONObject 對象是否存在某個 key。has
方法接受一個字符串參數,表示要檢查的 key,如果該 key 存在于 JSONObject 中,則返回 true,否則返回 false。
下面是一個示例代碼:
import org.json.JSONObject;
public class Main {public static void main(String[] args) {
// 創建一個 JSONObject 對象
JSONObject jsonObject = new JSONObject();
// 在 JSONObject 中添加一些 key-value 對
jsonObject.put("name", "Alice");
jsonObject.put("age", 25);
// 判斷是否存在某個 key
boolean hasName = jsonObject.has("name");
boolean hasGender = jsonObject.has("gender");
// 輸出結果
System.out.println("hasName:" + hasName);
System.out.println("hasGender:" + hasGender);
}
}
運行上述代碼,輸出結果為:
hasName: true
hasGender: false
可以看到,”name” key 存在于 JSONObject 中,而 ”gender” key 不存在。
丸趣 TV 網 – 提供最優質的資源集合!
正文完