简体   繁体   中英

Parsing JSON - Can't get boolean value from JsonObject

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

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

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

This is represented by the String result in the following:

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.

java.lang.ClassCastException: com.google.gson.JsonPrimitive cannot be cast to 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();

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();
    }

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

Try following

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

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是jsonObject

root.getBoolean("success");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM