繁体   English   中英

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 类是一个抽象类,它旨在通过提供进一步实现的子类使用,对于这些抽象类不够具体。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM