Structured Output and JSON Response Generation with Spring AI

In Spring AI, Structured Output bridges the gap between probabilistic, free-form text generation from Large Language Models (LLMs) and deterministic, strongly typed Java applications. Rather than forcing developers to manually write fragile JSON parsing logic or maintain complex formatting instructions inside prompts, Spring AI automatically guides the LLM to emit valid JSON and deserializes the output directly into Java records, POJOs, lists, or maps.

1. End-to-End Structured Output Lifecycle

Spring AI’s Structured Output API operates as a two-phase pipeline—Before the LLM Call (prompt enrichment) and After the LLM Call (response conversion and validation):
  1. Schema Generation (FormatProvider): Spring AI inspects the target Java class, record, or parameterized type at runtime and automatically generates a formal JSON Schema (Draft 2020-12) representing its fields, data types, nested objects, and constraints.

  2. Prompt Enrichment (getFormat()): Before sending the request to the model, Spring AI appends explicit formatting instructions—embedding the generated JSON Schema—to the prompt so the LLM understands the exact structure expected.

  3. Model Execution (Prompt-Based vs. Native JSON Mode):

    • Prompt-Guided Mode: Works across virtually any LLM provider by instructing the model via system/user formatting directives.

    • Native Structured Outputs / JSON Mode: When supported by the provider (such as OpenAI, Google Gemini, Anthropic Claude, or Ollama), Spring AI passes the JSON Schema directly in the API’s native response-format options, guaranteeing grammar-constrained token generation at the model level.

  4. Deserialization & Conversion (StructuredOutputConverter): Once the LLM returns its text payload, Spring AI strips any accidental markdown code fences (```json ... ```) and uses Jackson’s ObjectMapper (or Spring’s ConversionService) to deserialize the JSON into the requested Java type.

2. Built-In Output Converters

Spring AI provides a hierarchy of StructuredOutputConverter implementations tailored to different data shapes:

Converter Class Target Java Type Primary Mechanism & Use Case
BeanOutputConverter<T> Custom Java Classes, Java records, or generic collections via ParameterizedTypeReference Generates a full JSON Schema from the Java type definition and deserializes the LLM response via Jackson. Ideal for domain entities, nested DTOs, and typed lists.
MapOutputConverter Map<String, Object> Instructs the LLM to return an RFC 8259-compliant JSON object and converts it into key-value pairs. Ideal for dynamic schemas or unpredictable metadata keys.
ListOutputConverter List<String> Uses Spring’s ConversionService to instruct the LLM to emit a comma-delimited list and parses it into a clean string list. Ideal for tags, keywords, or simple enumerations.
3. High-Level ChatClient Integration (.entity())
While converters can be instantiated manually with the low-level ChatModel API, the ChatClient fluent API abstracts away converter setup through overloaded .entity() terminal methods:
  • Single Object Mapping: Passing a .class reference (e.g., an invoice summary record or product review class) automatically configures a BeanOutputConverter behind the scenes and returns the populated Java object directly.

  • Generic & Collection Mapping: Passing a ParameterizedTypeReference enables direct mapping into generic wrappers such as List<MovieRecommendation> or Map<String, ActorProfile> without type-erasure issues.

  • Custom Converter Injection: Passing a pre-configured StructuredOutputConverter instance allows customizing Jackson serialization rules or property ordering.

4. Schema Customization, Validation & Self-Correction

Production enterprise applications require strict guarantees around field descriptions, optionality, and schema adherence:
  • Schema Annotations (@JsonProperty, @JsonPropertyDescription): Annotating fields on Java classes or records enriches the generated JSON Schema with semantic descriptions and required-field flags. LLMs read these descriptions to populate ambiguous fields more accurately.

  • Property Ordering (@JsonPropertyOrder): Controls the exact sequence of fields in the generated JSON Schema, which helps guide autoregressive LLMs to generate reasoning or summary fields before generating final classification scores.

  • Automatic Validation & Retry (StructuredOutputValidationAdvisor): Even capable LLMs occasionally hallucinate invalid field types or miss required attributes when native JSON enforcement is unavailable. Spring AI provides a dedicated validation advisor that validates the LLM’s raw JSON output against the generated JSON Schema and automatically triggers corrective retry calls—feeding the validation error message back to the LLM—until valid JSON is produced.

5. Best Practices & Limitations

  • Prefer Java records for Output Models: Immutable Java records provide clean, concise definitions with predictable constructor binding for Jackson deserialization.

  • Enable Provider Native JSON / Schema Modes in Production: Whenever using Gemini, Claude, OpenAI, or Ollama, enable the provider’s native JSON Schema response option alongside .entity() to eliminate malformed syntax errors at the token generation layer.

  • Avoid Delimiter Collisions in Prompt Templates: Because JSON Schemas contain curly braces ({ and }), use custom template delimiters (such as <variable>) if embedding manual JSON examples inside PromptTemplate strings.

  • Incompatible with Token-by-Token Streaming: Structured output conversion requires a complete, syntactically valid JSON payload before deserialization can occur; therefore, .entity() is designed for synchronous .call() workflows rather than incremental .stream() responses.


Hands-on Experiment: AI-Based Resume Information Extractor using Spring AI Structured Output

Aim: To build a Spring Boot application that extracts structured information from resume text as JSON using Spring AI and stores it in MySQL.

Description: LLMs normally return free text, which is hard for applications to process reliably. Structured output makes the model respond in a defined JSON format that Spring AI converts directly into Java objects such as records or POJOs. It is used to extract fields like name, skills and experience from unstructured text and feed them into databases or APIs. This removes manual parsing and makes AI results dependable inside application code.

Software / Tools Required: JDK 17, Spring Boot 3.x, Maven, MySQL 8.x, IDE (IntelliJ/Eclipse/VS Code), Postman, and an OpenAI API key.

Step-by-Step Application Development

Step 1: Generate the Project via Spring Initializr

  • Project: Maven | Language: Java | Packaging: Jar | Java: 17
  • Spring Boot: 3.4.x (Spring AI 1.0 needs 3.4 or higher)
  • Group: com.example | Artifact: resume-extractor
  • Dependencies: Spring Web, Spring Data JPA, MySQL Driver, GeminiAI

Step 2: Project Structure

resume-extractor
├── pom.xml
└── src/main
    ├── java/com/example/resumeextractor
    │   ├── ResumeExtractorApplication.java
    │   ├── entity       (ResumeProfile)
    │   ├── repository   (ResumeProfileRepository)
    │   ├── service      (ResumeService)
    │   └── controller   (ResumeController)
    └── resources/application.properties

Step 3: Github Link: 

Step 4: Download the application from above github link, then test the below CURD operations

POST Payloads and URLs (Postman)

Use this same body for the three POST URLs:

json
{
  "resumeText": "Rahul Sharma | rahul.sharma@example.com | +91 98765 43210. Senior Java Developer with 6 years of experience. Skills: Java, Spring Boot, Hibernate, MySQL, Docker, AWS. Education: B.Tech in Computer Science, JNTU (2016); Oracle Certified Java Professional."
}

1. Bean output, saved to MySQL: POST http://localhost:8080/api/resumes/extract
Sample response:

json
{
  "id": 1, "fullName": "Rahul Sharma", "email": "rahul.sharma@example.com",
  "phone": "+91 98765 43210", "currentRole": "Senior Java Developer",
  "totalExperienceYears": 6, "skills": "Java, Spring Boot, Hibernate, MySQL, Docker, AWS",
  "education": "B.Tech in Computer Science, JNTU (2016); Oracle Certified Java Professional"
}

2. List output: POST http://localhost:8080/api/resumes/skills
3. Map output: POST http://localhost:8080/api/resumes/summary
4. All resumes: GET http://localhost:8080/api/resumes
5. One resume: GET http://localhost:8080/api/resumes/1
6. Search by skill: GET http://localhost:8080/api/resumes/search?skill=docker

Scroll to Top