简体   繁体   English

java.lang.UnsupportedOperationException: JsonObject - 不知道为什么

[英]java.lang.UnsupportedOperationException: JsonObject - Not sure why

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) 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?尽管我检查了 JSON 不为空,但知道为什么会出现此异常吗?

JsonElement Source code: https://github.com/google/gson/blob/master/gson/src/main/java/com/google/gson/JsonElement.java JsonElement 源代码: 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. JsonElement 类是一个抽象类,它旨在通过提供进一步实现的子类使用,对于这些抽象类不够具体。

The getAsString method exists, yes, but is implemented like this: 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());
  }

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.因此,为了获得您想要的结果,您需要在调用 getAsString() 之前将变量转换为您的子类。

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

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