我正在用Java开发一个minecraft插件,我正在尝试检查api是否给出了空键值。
我已经尝试过object.isJsonNull,但是似乎没有用。
这是我的代码:
try {
URL hypixel = new URL("https://api.hypixel.net/player?key=bd04adbb-7afc-42da-a833-09dbf09fbf06&name=" + username);
URLConnection urlConn = hypixel.openConnection();
urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
urlConn.getDoOutput();
if(args[0].equals("getxp")) {
try(final BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()))) {
final JsonParser parser = new JsonParser();
final JsonObject object = parser.parse(reader.readLine()).getAsJsonObject();
String exp = object.getAsJsonObject("player").get("networkExp").getAsString();
if(object.isJsonNull()) {
p.sendMessage(ChatColor.RED + "Player does not exist!");
}
p.sendMessage(ChatColor.GREEN + "EXP: " + exp);
}
}
感谢您的任何帮助!
这是我从api获得的响应
{"success":true,"player":null}
使用.has(String)和.isNull(String)
保守的用法可能是;
if (object.has("my_object_name") && !object.isNull("my_object_name")) {
// Do something with object.
}