google/gson · error · IOException

Incomplete document

Error message

Incomplete document

What it means

JsonTreeWriter.close() requires a complete, balanced document. If any container is still open (stack non-empty) when close() is called, it throws IOException("Incomplete document"). This catches unterminated beginObject()/beginArray() calls at close time, including when JsonWriter is used in a try-with-resources block that exits before all containers are closed.

Solutions

  1. Match every beginObject/beginArray with its end call before closing
  2. Use try-finally to ensure end calls run even when an exception is thrown
  3. Avoid try-with-resources on JsonWriter for partial writes; manage close() manually after confirming balance

Example fix

// before - try-with-resources closes with an open container
try (JsonWriter w = jsonWriter) {
  w.beginObject();
  w.name("a").value(1);
  // returns, close() throws: Incomplete document
}

// after - end the container before close
try (JsonWriter w = jsonWriter) {
  w.beginObject();
  w.name("a").value(1);
  w.endObject();
}
Defensive patterns

Strategy: validation

Validate before calling

// Ensure all containers are closed before close()
if (openContainers != 0) {
    throw new IllegalStateException("Cannot close: " + openContainers + " open containers");
}
writer.close();

Try / catch

try {
  writer.close();
} catch (IOException e) {
  // 'Incomplete document': an open container remains; end it then close again
}

Prevention

When it happens

Trigger: Calling close() (often via try-with-resources on JsonWriter) before all beginObject/beginArray calls have matching end calls; an exception mid-serialization that unwinds to the implicit close.

Common situations: try-with-resources on JsonWriter where the body throws or returns early; mismatched begin/end; streaming serialization that aborts partway through.

Related errors


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

Appendix: source

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

  @CanIgnoreReturnValue
  @Override
  public JsonWriter nullValue() throws IOException {
    put(JsonNull.INSTANCE);
    return this;
  }

  @Override
  public JsonWriter jsonValue(String value) throws IOException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void flush() throws IOException {}

  @Override
  public void close() throws IOException {
    if (!stack.isEmpty()) {
      throw new IOException("Incomplete document");
    }
    stack.add(SENTINEL_CLOSED);
  }
}

View on GitHub (pinned to 310ac341f2)