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

JsonTreeWriter.name() throws IllegalStateException("Please begin an object before writing a name.") when the current open container is an array, not an object. JSON member names (keys) are only valid inside JSON objects; arrays contain positional values only. Calling name() inside an array is a structural error.

Solutions

  1. Call name() only inside an object (beginObject), never inside an array (beginArray)
  2. If key-value pairs are needed, open with beginObject() rather than beginArray()
  3. Track and check the current container type before emitting a name

Example fix

// before - name inside an array
writer.beginArray();
writer.name("x");

// after - use an object for keyed members
writer.beginObject();
writer.name("x").value(1);
Defensive patterns

Strategy: validation

Validate before calling

// Only call name() when the current container is a JsonObject
if (!(topOfStack instanceof JsonObject)) {
    throw new IllegalStateException("name() requires an object container, not an array");
}
writer.name(key);

Try / catch

try {
  writer.name(key);
} catch (IllegalStateException e) {
  // 'Please begin an object...': switch from beginArray() to beginObject(), or drop the name()
}

Prevention

When it happens

Trigger: Calling name() after beginArray() instead of beginObject(); misidentifying the current container type in a custom adapter; code that assumes an object context but opened an array.

Common situations: Refactor that swapped container types; adapter logic that branches on the wrong container; copy-paste of keyed emission into array code.

Related errors


AI-assisted analysis of google/gson@310ac341f2 (2026-08-10). Data as JSON: /api/errors/150114207e8209e7. Report an issue: GitHub.

Appendix: source

Thrown at gson/src/main/java/com/google/gson/internal/bind/JsonTreeWriter.java:157

      stack.remove(stack.size() - 1);
      return this;
    }
    throw new IllegalStateException();
  }

  @CanIgnoreReturnValue
  @Override
  public JsonWriter name(String name) throws IOException {
    Objects.requireNonNull(name, "name == null");
    if (stack.isEmpty() || pendingName != null) {
      throw new IllegalStateException("Did not expect a name");
    }
    JsonElement element = peek();
    if (element instanceof JsonObject) {
      pendingName = name;
      return this;
    }
    throw new IllegalStateException("Please begin an object before writing a name.");
  }

  @CanIgnoreReturnValue
  @Override
  public JsonWriter value(String value) throws IOException {
    if (value == null) {
      return nullValue();
    }
    put(new JsonPrimitive(value));
    return this;
  }

  @CanIgnoreReturnValue
  @Override
  public JsonWriter value(boolean value) throws IOException {
    put(new JsonPrimitive(value));
    return this;
  }

View on GitHub (pinned to 310ac341f2)