GSON JsonObject “Unsupported Operation Exception: null” getAsString

匿名 (未验证) 提交于 2019-12-03 01:45:01

问题:

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



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!