[英]Parsing JSON - Can't get boolean value from JsonObject
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 result
in 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. 我需要将“success”参数作为布尔值。 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"?
如何获得“成功”的博尔价值?
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();
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();
}
you're calling root.getAsJsonObject("success")
while the success
is 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();
I would just use the root.get("success") method. 我只想使用root.get(“success”)方法。 Success isn't really a json object, it's a member of a json object.
成功不是真正的json对象,它是json对象的成员。 See here https://google.github.io/gson/apidocs/com/google/gson/JsonObject.html#get-java.lang.String-
请参阅此处https://google.github.io/gson/apidocs/com/google/gson/JsonObject.html#get-java.lang.String-
如果root是jsonObject
root.getBoolean("success");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.