GSON JsonObject “Unsupported Operation Exception: null” getAsString

后端 未结 4 942
无人共我
无人共我 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<Type> 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<Type> 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<Type> 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

    0 讨论(0)
  • 2020-12-09 15:21

    I had a similar problem and I had to change jsonObject.getAsString() to jsonObject.toString();

    0 讨论(0)
  • 2020-12-09 15:22

    In my case I just needed to get the element as an empty string if it is null, so I wrote a function like this:

    private String getNullAsEmptyString(JsonElement jsonElement) {
            return jsonElement.isJsonNull() ? "" : jsonElement.getAsString();
        }
    

    So instead of

    val geocoder = json.getAsString
    

    You can just use this

    val geocoder = getNullAsEmptyString(json);
    

    It returns "" if the element is null and the actual string if it is not

    0 讨论(0)
  • 2020-12-09 15:27

    Maybe your JsonElement is a JsonNull

    What you could do is to first check that it isn't by using json.isJsonNull

    Otherwise, try to get its String representation with json.toString

    0 讨论(0)
提交回复
热议问题