I have the following code:
JsonElement deviceConfig = null;
JsonObject status = getRestAPI().Connectivity().getDeviceStatus(device);
deviceConfig = status.get("deviceConfig");
if (deviceConfig == null || deviceConfig.isJsonNull()) {
deviceConfig = status.get("mConfig");
}
if (deviceConfig != null && !deviceConfig.isJsonNull()) {
if (!deviceConfig.getAsString().isEmpty()) {
break;
}
}
For some reasons, I get the following error:
java.lang.UnsupportedOperationException: JsonObject at com.google.gson.JsonElement.getAsString(JsonElement.java:191)
In this line:
if (!deviceConfig.getAsString().isEmpty()) {
Any idea why I get this exception although I checked that the JSON is not null?
JsonElement Source code: https://github.com/google/gson/blob/master/gson/src/main/java/com/google/gson/JsonElement.java
The JsonElement class is an abstract class, it's meant to be used through subclasses that provide further implementations, for which the abstract class isn't concrete enough.
The getAsString method exists, yes, but is implemented like this:
/**
* convenience method to get this element as a string value.
*
* @return get this element as a string value.
* @throws ClassCastException if the element is of not a {@link JsonPrimitive} and is not a valid
* string value.
* @throws IllegalStateException if the element is of the type {@link JsonArray} but contains
* more than a single element.
*/
public String getAsString() {
throw new UnsupportedOperationException(getClass().getSimpleName());
}
Which basically means: you are expected to provide an implementation in your subclass.
So, in order to get the result you desire, you'll need to cast the variable to your subclass before calling getAsString() on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With