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
- Match every beginObject/beginArray with its end call before closing
- Use try-finally to ensure end calls run even when an exception is thrown
- 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
- Match every begin with an end before close()
- Use try-finally to guarantee end calls on exception paths
- Avoid try-with-resources on JsonWriter for partial writes; close manually after confirming balance
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
- Did not expect a name
- Expected one JSON element but was
- Please begin an object before writing a name.
- Already wrote a name, expecting a value.
- Dangling name
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)