google/gson · error · IllegalStateException

Not a JSON Null: {this}

Error message

Not a JSON Null: {this}

What it means

Thrown by JsonElement.getAsJsonNull() when the element is not a JsonNull. This accessor is mostly used to assert/verify that a value is the JSON null token; calling it on any other element type fails.

Source

Thrown at gson/src/main/java/com/google/gson/JsonElement.java:211

    }
    throw new IllegalStateException("Not a JSON Primitive: " + this);
  }

  /**
   * Convenience method to get this element as a {@link JsonNull}. If this element is of some other
   * type, an {@link IllegalStateException} will result. Hence it is best to use this method after
   * ensuring that this element is of the desired type by calling {@link #isJsonNull()} first.
   *
   * @return this element as a {@link JsonNull}.
   * @throws IllegalStateException if this element is of another type.
   * @since 1.2
   */
  @CanIgnoreReturnValue // When this method is used only to verify that the value is JsonNull
  public JsonNull getAsJsonNull() {
    if (isJsonNull()) {
      return (JsonNull) this;
    }
    throw new IllegalStateException("Not a JSON Null: " + this);
  }

  /**
   * Convenience method to get this element as a boolean value.
   *
   * @return this element as a primitive boolean value.
   * @throws UnsupportedOperationException if this element is not a {@link JsonPrimitive} or {@link
   *     JsonArray}.
   * @throws IllegalStateException if this element is of the type {@link JsonArray} but contains
   *     more than a single element.
   */
  public boolean getAsBoolean() {
    throw new UnsupportedOperationException(getClass().getSimpleName());
  }

  /**
   * Convenience method to get this element as a {@link Number}.
   *

View on GitHub (pinned to 8b8628c656)

Solutions

  1. Use isJsonNull() as the predicate instead of calling getAsJsonNull() to test for null.
  2. Only call getAsJsonNull() after isJsonNull() returns true, if you need the typed JsonNull reference.
  3. For nullable fields, branch on isJsonNull() and skip processing.

Example fix

// before
if (el.getAsJsonNull() != null) { ... } // throws if el is not null
// after
if (el.isJsonNull()) { ... }
Defensive patterns

Strategy: validation

Validate before calling

// Use the predicate, not the cast, to test for null
boolean isNull = el != null && el.isJsonNull();

Type guard

boolean isJsonValueNull(JsonElement e) { return e != null && e.isJsonNull(); }

Prevention

When it happens

Trigger: Calling element.getAsJsonNull() on a non-null element to 'confirm' nullness, or misusing it instead of isJsonNull().

Common situations: Confusing getAsJsonNull() (a cast) with isJsonNull() (a predicate); defensive code that calls getAsJsonNull() without first checking.

Related errors


AI-assisted analysis of google/gson@8b8628c656 (2026-08-04). Data as JSON: /data/errors/7d1dc2c8c7062769.json. Report an issue: GitHub.