判断JSONObject是否存在对象
可以使用has方法来判断JSONObject中是否存在某个key对应的对象。如果存在该key,则返回true,否则返回false。
示例代码如下:
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
String jsonStr = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
JSONObject jsonObject = new JSONObject(jsonStr);
boolean hasName = jsonObject.has("name");
boolean hasAddress = jsonObject.has("address");
System.out.println("Has name: " + hasName);
System.out.println("Has address: " + hasAddress);
}
}
输出结果:
Has name: true
Has address: false
在上面的例子中,判断JSONObject是否存在"name"键的对象,返回结果为true;判断是否存在"address"键的对象,返回结果为false
原文地址: https://www.cveoy.top/t/topic/hNVX 著作权归作者所有。请勿转载和采集!