java.lang.UnsupportedOperationException:JsonObject - 不确定原因

java.lang.UnsupportedOperationException: JsonObject - Not sure why

我有以下代码:


    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;
        }
    }

由于某些原因,我收到以下错误:

java.lang.UnsupportedOperationException: JsonObject at com.google.gson.JsonElement.getAsString(JsonElement.java:191)

这一行:

if (!deviceConfig.getAsString().isEmpty()) {

虽然我检查了 JSON 不为空,但知道为什么我会收到此异常吗?

JsonElement 源代码:https://github.com/google/gson/blob/master/gson/src/main/java/com/google/gson/JsonElement.java

JsonElement class 是一个抽象 class,它旨在通过提供进一步实现的子 classes 使用,抽象 class 不是不够具体。

getAsString 方法存在,是的,但是是这样实现的:

  /**
   * 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());
  }

这基本上意味着:您应该在子class中提供一个实现。

因此,为了获得您想要的结果,您需要在调用 getAsString() 之前将变量转换为子class。