Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GSON JsonObject "Unsupported Operation Exception: null" getAsString

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.

like image 853
crockpotveggies Avatar asked Feb 17 '12 08:02

crockpotveggies


3 Answers

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

like image 153
Andy Petrella Avatar answered Sep 28 '22 03:09

Andy Petrella


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

like image 34
lleclerc Avatar answered Sep 28 '22 02:09

lleclerc


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

like image 25
Henry Avatar answered Sep 28 '22 02:09

Henry