google/gson · error · IllegalStateException

Please begin an object before writing a name.

Error message

Please begin an object before writing a name.

What it means

Thrown by JsonWriter.name() when the current scope is neither EMPTY_OBJECT nor NONEMPTY_OBJECT. Property names are only valid inside a JSON object, so calling name() at the document root, inside an array, or before beginObject() is rejected to prevent malformed JSON.

Source

Thrown at gson/src/main/java/com/google/gson/stream/JsonWriter.java:506

  private void replaceTop(int topOfStack) {
    stack[stackSize - 1] = topOfStack;
  }

  /**
   * Encodes the property name.
   *
   * @param name the name of the forthcoming value. May not be {@code null}.
   * @return this writer.
   */
  @CanIgnoreReturnValue
  public JsonWriter name(String name) throws IOException {
    Objects.requireNonNull(name, "name == null");
    if (deferredName != null) {
      throw new IllegalStateException("Already wrote a name, expecting a value.");
    }
    int context = peek();
    if (context != EMPTY_OBJECT && context != NONEMPTY_OBJECT) {
      throw new IllegalStateException("Please begin an object before writing a name.");
    }
    deferredName = name;
    return this;
  }

  private void writeDeferredName() throws IOException {
    if (deferredName != null) {
      beforeName();
      string(deferredName);
      deferredName = null;
    }
  }

  /**
   * Encodes {@code value}.
   *
   * @param value the literal string value, or null to encode a null literal.
   * @return this writer.

View on GitHub (pinned to 8b8628c656)

Solutions

  1. Call writer.beginObject() before any name() call, and endObject() after the last value.
  2. Verify the call ordering: name() is only valid between beginObject() and endObject().
  3. When writing array elements, use value()/beginObject() per element rather than name().
  4. Restructure so that object membership is established before names are written.

Example fix

// before
writer.name("x").value(1); // throws: no object started
writer.endObject();

// after
writer.beginObject();
writer.name("x").value(1);
writer.endObject();
Defensive patterns

Strategy: validation

Validate before calling

// Ensure beginObject() precedes name()
writer.beginObject();
try {
  writer.name("x").value(1);
} finally {
  writer.endObject();
}

Prevention

When it happens

Trigger: Calling writer.name("x") before beginObject(), or inside an array (where elements, not names, are expected), or at the top level of the document.

Common situations: Forgetting to call beginObject() before writing fields; writing object-style code into an array context; porting serialization logic and losing the enclosing beginObject().

Related errors


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