How do I map structured AI output to Java records?

In Part 2, our Java assistant used prompt templates to match the reader’s skill level. Now we will add POST /api/explain and return a summary, key points, and Java code as separate fields. Keep the existing /api/ask controller alongside this new endpoint.

Set up the project

Use JDK 25 and Maven 3.9 or later. This article retains Spring Boot 4.1.2 and Spring AI 2.0.2 from Parts 1 and 2. Spring’s compatibility guide supports Boot 4.1.x with AI 2.0.x. Use the complete POM at the end.

Configure the model

File: src/main/resources/application.properties

server.address=127.0.0.1
spring.ai.openai.api-key=${OPENAI_API_KEY}
spring.ai.openai.chat.model=gpt-4o-mini

Use an OpenAI API key with access to the selected model. Never commit credentials or include them in requests or logs. API usage has separate billing from a ChatGPT subscription.

Keep the application entry point

File: src/main/java/org/kodejava/springai/JavaAssistantApplication.java

package org.kodejava.springai;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class JavaAssistantApplication {
    public static void main(String[] args) {
        SpringApplication.run(JavaAssistantApplication.class, args);
    }
}

Define a response record

File: src/main/java/org/kodejava/springai/JavaExplanation.java

package org.kodejava.springai;

import java.util.List;

public record JavaExplanation(String summary, List<String> keyPoints,
                              String exampleCode) {
}

The record describes the expected data. Its generated accessors include summary() and keyPoints(). A UI can display each field separately. A record does not validate its contents or make a contained list immutable.

Add the endpoint

File: src/main/java/org/kodejava/springai/JavaExplanationController.java

package org.kodejava.springai;

import java.util.Locale;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

@RestController
public class JavaExplanationController {
    private final ChatClient client;

    public JavaExplanationController(ChatClient.Builder builder) {
        this.client = builder.build();
    }

    @PostMapping("/api/explain")
    public JavaExplanation explain(@RequestBody ExplainRequest request) {
        if (request.question() == null || request.question().isBlank()) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                    "Question must not be blank");
        }
        String level = request.level() == null ? "beginner"
                : request.level().strip().toLowerCase(Locale.ROOT);
        String guidance = switch (level) {
            case "beginner" -> "Define unfamiliar terms with a concrete example.";
            case "intermediate" -> "Assume knowledge of classes; explain tradeoffs.";
            case "advanced" -> "Discuss contracts, edge cases, and design implications.";
            default -> throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                    "Level must be beginner, intermediate, or advanced");
        };
        JavaExplanation result = client.prompt()
                .system(s -> s.text("""
                        You are a Java 25 tutor writing plain English.
                        Reader level: {level}. Teaching guidance: {guidance}
                        Provide a short summary, three useful key points,
                        and one small Java example. In exampleCode, use
                        Java source without Markdown fences.
                        Answer the question in the user message.
                        """).param("level", level).param("guidance", guidance))
                .user(request.question())
                .call()
                .entity(JavaExplanation.class);
        if (result == null || result.summary() == null || result.summary().isBlank()
                || result.keyPoints() == null || result.keyPoints().size() != 3
                || result.keyPoints().stream().anyMatch(p -> p == null || p.isBlank())
                || result.exampleCode() == null || result.exampleCode().isBlank()) {
            throw new ResponseStatusException(HttpStatus.BAD_GATEWAY,
                    "Model returned an incomplete explanation");
        }
        return result;
    }

    public record ExplainRequest(String question, String level) {}
}

The skill-level template follows Part 2. Omitting level selects beginner guidance; an empty or unknown value returns HTTP 400 before a model call. The question stays in a separate user message.

The key change is .call().entity(JavaExplanation.class) instead of .call().content(). Spring AI derives a JSON schema from the record, requests structured output, and converts the model reply into the record. Spring MVC then serializes that Java object into HTTP JSON. No manual string splitting is needed.

The application check enforces useful content and exactly three points. Declaring List<String> alone does not require three elements. A parsed but incomplete answer returns HTTP 502. A conversion exception happens before this check and normally produces HTTP 500 in this minimal application. Provider failures also propagate; a later article will add a consistent exception handler.

Understand the limits

Basic entity() is best effort. A model can produce output that cannot be converted. Successful parsing does not prove factual correctness or that generated Java compiles. Review code before using it and never execute it automatically.

Spring AI also provides provider-native structured output and schema validation with self-correction. Those features improve structural reliability but do not establish factual accuracy. Retries can add latency and cost. We will introduce reliability policies separately. Typed conversion requires the complete response, so this example uses call(), not stream().

Build and run

Check java -version and mvn -version; Maven should use JDK 25. Build from the project directory:

mvn clean package

In Bash on Linux or macOS, read the key without adding it to shell history:

read -r -s -p 'OpenAI API key: ' OPENAI_API_KEY
printf '\n'
export OPENAI_API_KEY
mvn spring-boot:run

In PowerShell 7.2 or later:

$env:OPENAI_API_KEY = Read-Host 'OpenAI API key' -MaskInput
mvn spring-boot:run

Run Maven in the same terminal. Masking hides input; the credential still exists in the process environment. Stop with Ctrl+C, then clear it using unset OPENAI_API_KEY in Bash or Remove-Item Env:OPENAI_API_KEY in PowerShell.

Send a request

From another Unix terminal:

curl -i http://127.0.0.1:8080/api/explain -H 'Content-Type: application/json' -d '{"question":"How do Java records reduce boilerplate?","level":"beginner"}'

In PowerShell:

$body = @{ question = 'How do Java records reduce boilerplate?'; level = 'beginner' } | ConvertTo-Json
Invoke-RestMethod -Uri 'http://127.0.0.1:8080/api/explain' -Method Post -ContentType 'application/json' -Body $body | ConvertTo-Json -Depth 5

An illustrative HTTP 200 response:

{
  "summary": "Records provide a concise way to declare data classes.",
  "keyPoints": [
    "The header declares the components.",
    "Java generates accessors, equals, hashCode, and toString.",
    "Component fields are final, but referenced objects can be mutable."
  ],
  "exampleCode": "record Person(String name, int age) {}"
}

Wording and code vary. The response has fields directly rather than an answer string containing JSON. Escaped line breaks inside a JSON code string are normal.

Request or condition Expected behavior
Valid question without level Beginner guidance; HTTP 200 if conversion and checks succeed
Level ADVANCED Advanced guidance after normalization
Blank question HTTP 400; no model call
Level expert HTTP 400; no model call
Parsed answer missing required content HTTP 502
Unconvertible model output Server error; no successful record response

Error body details depend on Spring Boot configuration. For provider 401 errors, check the running process’s key. For 429, inspect billing and rate limits. Do not print the credential while troubleshooting.

Try it yourself

Compare the same question at all three levels while checking that the field names stay consistent. Next add an exercise component, update the prompt, and validate that field. Decide which rules need explicit application checks.

Part 4 will introduce Ollama. Later articles will build document question answering with PostgreSQL vector search and Java tool calling, then progress to evaluation and operational concerns.

References

Maven artifacts

File: pom.xml. Maven Central is sufficient. The Boot parent manages the web starter and plugin; the AI BOM manages the OpenAI starter.

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>4.1.2</version>
        <relativePath/>
    </parent>
    <groupId>org.kodejava</groupId>
    <artifactId>spring-ai-java-assistant</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
        <java.version>25</java.version>
        <spring-ai.version>2.0.2</spring-ai.version>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.ai</groupId>
                <artifactId>spring-ai-bom</artifactId>
                <version>${spring-ai.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webmvc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-starter-model-openai</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
Wayan

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.