java 解析 JSON - 无法从 JsonObject 获取布尔值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37889026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:55:17  来源:igfitidea点击:

Parsing JSON - Can't get boolean value from JsonObject

javajsongson

提问by I wrestled a bear once.

I've been trying to figure out how to do some basic stuff in Java..

我一直在试图弄清楚如何在 Java 中做一些基本的事情..

I've got a request being made to an API, which returns the following JSON.

我收到了一个对 API 的请求,它返回以下 JSON。

{"success": false, "message": "some string", "data": []}

This is represented by the String resultin the following:

这由以下字符串表示result

JsonObject root = new JsonParser().parse(result).getAsJsonObject();
success = root.getAsJsonObject("success").getAsBoolean();

I need to get the "success" parameter as a boolean. Getting an error on the getAsBoolean()call.

我需要将“成功”参数作为布尔值获取。getAsBoolean()通话出错。

java.lang.ClassCastException: com.google.gson.JsonPrimitive cannot be cast to com.google.gson.JsonObject

java.lang.ClassCastException: com.google.gson.JsonPrimitive 无法转换为 com.google.gson.JsonObject

What am I doing wrong? How do I get the bool value of "success"?

我究竟做错了什么?如何获得“成功”的布尔值?

回答by ΦXoc? ? Пepeúpa ツ

The reason that is breaking your code is that you are calling the wrong method...

破坏你的代码的原因是你调用了错误的方法......

Do

success = root.get("success").getAsBoolean();

instead of

代替

success = root.getAsJsonObject("success").getAsBoolean();

Example:

例子:

public static void main(String[] args) {
    String result = "{\"success\": false, \"message\": \"some string\", \"data\": []}";
    JsonObject root = new JsonParser().parse(result).getAsJsonObject();
    boolean success = root.get("success").getAsBoolean();
    }

回答by ikryvorotenko

you're calling root.getAsJsonObject("success")while the successis a boolean value itself, not an object.

您在调用root.getAsJsonObject("success")时调用的success是布尔值本身,而不是对象。

Try following

尝试以下

JsonObject root = new JsonParser().parse(result).getAsJsonObject();
success = root.get("success").getAsBoolean();

回答by Dalton D

I would just use the root.get("success") method. Success isn't really a json object, it's a member of a json object. See here https://google.github.io/gson/apidocs/com/google/gson/JsonObject.html#get-java.lang.String-

我只会使用 root.get("success") 方法。成功并不是真正的 json 对象,而是 json 对象的成员。请参阅此处https://google.github.io/gson/apidocs/com/google/gson/JsonObject.html#get-java.lang.String-

回答by zardilior

If root is a jsonObject

如果 root 是一个 jsonObject

root.getBoolean("success");