GSON JsonObject “Unsupported Operation Exception:

2019-01-18 09:10发布

问题:

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 information as expected. However, the problem is when I try to actually run methods on that JsonElement.

val json = WS.url("http://maps.googleapis.com/maps/api/geocode/json?callback=?&sensor=true&address=%s", startAddress+","+startCity+","+startProvince).get.getJson
    val geocoder = json.getAsString

The only error I get back is Unsupported Operation Exception: null and I've tried this on getAsString and getAsJsonObject and getAsJsonPrimitive

Any idea why it's failing on all methods? Thanks.

回答1:

Maybe be 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



回答2:

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



回答3:

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