【问题标题】:How would i check if the returned object is null in gson我将如何检查返回的对象在 gson 中是否为空
【发布时间】:2020-09-09 17:05:54
【问题描述】:

我正在用 java 制作一个 minecraft 插件,我正在尝试检查 api 是否给出了 null 键值。

我已经尝试过 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}

【问题讨论】:

  • 在尝试调用方法后,您是否希望空测试能够正常工作?

标签: java api gson minecraft


【解决方案1】:

使用 .has(String) 和 .isNull(String)

保守的用法可能是;

if (object.has("my_object_name") && !object.isNull("my_object_name")) {
    // Do something with object.
  }

【讨论】:

    猜你喜欢
    • 2013-10-11
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    相关资源
    最近更新 更多