Module 09: Structured Outputs
Getting Claude to return structured JSON responses.What You’ll Learn
- Using
JsonSchemato define output structure - Configuring structured outputs with
CLIOptions - Parsing JSON responses with Jackson
Why Structured Outputs?
Instead of parsing free-form text, get Claude to return predictable JSON:Defining a Schema
UseJsonSchema to define the expected output structure:
Using Structured Outputs
Structured outputs requireCLIOptions with ClaudeSyncClient:
Nested Schemas
Define complex structures with arrays and nested objects:JsonSchema Methods
| Method | Description |
|---|---|
JsonSchema.ofObject(properties, required) | Create object schema with required fields |
JsonSchema.ofObject(properties) | Create object schema (all optional) |
JsonSchema.fromMap(map) | Create from existing Map |
schema.toMap() | Convert to Map for CLIOptions |
JSON Types Reference
| Type | JSON Schema | Java Type |
|---|---|---|
| String | "type": "string" | String |
| Number | "type": "number" | double |
| Integer | "type": "integer" | int |
| Boolean | "type": "boolean" | boolean |
| Array | "type": "array" | List |
| Object | "type": "object" | Map or POJO |
Note on Query API
The simplifiedQueryOptions class does not support jsonSchema. Use CLIOptions with ClaudeSyncClient for structured outputs.
Limitations
- No strict enforcement: Claude attempts to match your schema but may occasionally produce invalid JSON or missing fields. Always validate the response.
- Schema complexity: Deeply nested schemas (>3-4 levels) or schemas with many optional fields increase the chance of malformed output.
- Error handling: When Claude fails to produce valid JSON, you receive raw text. Wrap parsing in try-catch:
- No partial results: If Claude’s response is truncated (due to
maxTokens), the JSON will be incomplete and unparseable. - Tool use interactions: When Claude uses tools during a structured output request, intermediate messages are unstructured. Only the final response follows the schema.