Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.UnsupportedOperationException: JsonObject - Not sure why

Tags:

java

gson

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?

like image 930
TheUnreal Avatar asked Sep 16 '25 14:09

TheUnreal


1 Answers

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.

like image 163
Stultuske Avatar answered Sep 18 '25 08:09

Stultuske