Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk5 min

A Guide to Structured Output in Spring AI

Spring AI's .entity() converts completed model responses into Java types. Learn how to handle generic targets and choose between prompt guidance, validation, and provider-native structured output.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a typed response from Spring AI, start with ChatClient.prompt()...call().entity(MyType.class). Spring AI uses the target type to guide the model toward a JSON shape and converts the completed response into that type. It is a useful way to get data into Java code, but it is best-effort unless you add validation or use a provider and model that support native structured output.

Get a typed response with .entity()

For a concrete Java class or record, use .entity(Target.class) after .call(). The high-level API derives a schema from the target type, includes formatting guidance in the model request, and converts the returned text. For example:

record ActorsFilms(String actor, List<String> films) {}

ActorsFilms result = chatClient.prompt()
    .user("List films starring Keanu Reeves")
    .call()
    .entity(ActorsFilms.class);

The exact record fields should reflect the data your application needs. This conversion saves you from manually mapping a text response, but it does not establish that the model’s answer is true or complete. See Spring AI’s Structured Output reference for the documented call flow and examples.

Handle generic types and response metadata

Lists and maps

Java erases generic type parameters at runtime, so a raw List.class does not express the element type. Supply a ParameterizedTypeReference for a generic target:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
List<ActorsFilms> results = chatClient.prompt()
    .user("List actors and films")
    .call()
    .entity(new ParameterizedTypeReference<List<ActorsFilms>>() {});

The same approach applies to generic maps, such as Map<String, MyType>. Use the type reference that matches the structure you expect rather than relying on a raw container. The Structured Output reference documents typed targets and generic handling.

Keep the model response as well as the object

If application logic also needs the ChatResponse—for example, response metadata—use the documented responseEntity(...) option rather than discarding everything except the converted value. The API details and overloads are described in the Structured Output reference.

Choose an output converter for the shape you need

Spring AI’s StructuredOutputConverter<T> combines Spring’s Converter<String,T> with FormatProvider: it can provide format instructions before generation and convert response text afterwards. The built-in choices have different output expectations:

Converter Use it for Output approach
BeanOutputConverter<T> A class, record, or parameterized target type Derives a JSON Schema and deserializes JSON into the target
MapOutputConverter A flexible object represented as Map<String,Object> Guides output toward RFC 8259 JSON
ListOutputConverter A list of converted values Guides output toward comma-delimited values and converts them through a ConversionService

For ordinary typed replies, .entity(...) is the most direct interface. Use a custom converter when the built-in target formats or parsing behavior do not fit. Structured output converters are not the mechanism for LLM tool calling; tool calling is a separate feature. Spring AI’s Output Converters reference covers the interface and converter types.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Know what a successful conversion does—and does not—prove

By default, structured output is best-effort. Spring AI can add schema instructions to the request and parse the returned text, but the model may still produce malformed JSON, omit or add fields, or include prose. Even when conversion succeeds, the resulting object can contain incorrect, irrelevant, or unsupported claims. Treat parsing as a shape-conversion step, not semantic verification.

The documented .entity(...) path requires a completed response and is available after .call(); it is not a typed streaming API. A streaming response yields text chunks, so code that needs a typed entity must wait for completion and then convert. These boundaries and the best-effort behavior are described in the Structured Output reference and Output Converters reference.

Improve shape reliability with validation or provider-native output

Prompt-based conversion

The default approach supplies formatting instructions as text, then converts the result. It is broadly compatible, but the model is being guided rather than technically constrained to satisfy the schema. Use it when a parse failure can be handled safely and provider compatibility is more important than strict shape enforcement.

Schema validation and retry

Spring AI documents validateSchema() as a way to validate structured output and retry when it fails validation. The validation reference documents a default of three retry attempts for StructuredOutputValidationAdvisor; verify the default against the Spring AI version used by your application. Validation can improve structural reliability, but define application-level checks for required meaning, allowed values, business rules, and factual plausibility as well.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

See Schema Validation & Self-Correction for the validation path and configuration details.

Provider-native structured output

useProviderStructuredOutput() asks a supported provider to send the schema through its API-level structured-output mechanism. Spring AI leaves this off by default for compatibility: an older or unsupported model may reject such a request, whereas prompt-based instructions work across a broader range of integrations.

Native support is not uniform. Provider and model versions can differ in their supported JSON Schema features; Spring AI specifically notes potential limitations with $ref, deeply nested arrays, allOf/anyOf/oneOf, regular-expression patterns, and recursive types. Its reference also notes model-specific variability for Ollama. Check the concrete provider and model documentation, then test the schema your application actually sends. Provider-Native Structured Output describes the compatibility and schema constraints.

Combine enforcement and validation when failures matter

Provider-native output and validation address different failure points: native mode requests schema enforcement at generation time, while validation checks the output Spring AI receives and can trigger retries. The documented options can be combined. Select based on provider support, schema complexity, the cost of a malformed result, and whether retries are acceptable; neither path replaces semantic or domain validation.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Check version-sensitive behavior before adopting examples

Spring AI’s reference pages are rolling documentation, so API names, defaults, provider support, and schema behavior should be checked against the version in your project. In particular, upgrade notes describe changes to BeanOutputConverter after it began delegating schema generation to JsonSchemaGenerator. For the affected release, the notes say Kotlin optional primary-constructor properties are no longer listed as required; @JsonProperty(required = false) and annotations without an explicit required value are no longer treated as required; primitive schemas gain OpenAPI-style format hints such as int32, int64, and date-time; and BeanOutputConverter.postProcessSchema(JsonNode) was removed. These are upgrade-specific changes, not timeless rules for every Spring AI release. Consult the Spring AI Upgrade Notes for the release relevant to your application.

A practical choice for an application

  • Use .entity(MyType.class) for a concrete type and ParameterizedTypeReference for generic containers.
  • Choose responseEntity(...) if the typed value is not enough and you also need response metadata.
  • Use the default prompt-guided path when broad compatibility is the priority and your application can handle malformed or semantically invalid values.
  • Add validation and retries when shape failures need a recovery path; use provider-native output when the selected provider and model support the schema you need.
  • Test conversion, schema support, validation behavior, and failure handling with the actual provider, model version, Spring AI version, and target type used in production.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.