GSON JsonObject “Unsupported Operation Exception: null” getAsString

后端 未结 4 954
无人共我
无人共我 2020-12-09 14:27

Running a Play! app with Scala. I\'m doing a request where the response is expected to be a JSON string. When checking the debugger, the JsonElement returns OK with all info

4条回答
  •  轮回少年
    2020-12-09 15:02

    The class JsonElement will throw Unsupported Operation Exception for any getAs method, because it's an abstract class and makes sense that it is implemented in this way.

    For some reason the class JsonObject, does not implement the getAs methods, so any call to one of these methods will throw an exception.

    Calling the toString method on a JsonElement object, may solve your issue in certain circumstances, but isn't probably what you want because it returns the json representation as String (e.g. \"value\") in some cases.

    I found out that also a JsonPrimitive class exists and it does implement the getAs methods. So probably the correct way to proceed is something like this:

        String input = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
        JsonParser parser = new JsonParser();
        JsonElement jsonTree = parser.parse(input);
    
        if(jsonTree != null && jsonTree.isJsonObject()) {
            JsonObject jsonObject = jsonTree.getAsJsonObject();
            value = jsonObject.get("key1").getAsJsonPrimitive().getAsString()
        }
    

    PS. I removed all the nullability mgmt part. If you are coding in Java you probably want to manage this in a better way.

    see GitHub source code for JsonElement: https://github.com/google/gson/blob/master/gson/src/main/java/com/google/gson/JsonElement.java#L178

提交回复
热议问题