Spring › Spring-AI

Enforcing Gemini JSON output with Spring AI BeanOutputConverter

Combine Spring AI 2.0.1 BeanOutputConverter with Gemini native JSON Schema to deserialize nested Kotlin DTOs and enums without retry loops.

Enforcing Gemini JSON output with Spring AI BeanOutputConverter

When you wire an LLM into backend business logic, the most common failure mode isn’t model quality—it’s broken JSON. Models wrap payloads in markdown fences ( ``json ), add conversational preambles, or invent enum strings that crash Jackson deserialization. This post combines Spring AI 2.0.1's BeanOutputConverter with Google Gemini's provider-native JSON Schema (constrained decoding) and fixes a $ref/$defs` bug that breaks nested Kotlin DTOs and shared enums.

Tested with Spring Boot 4.1.1, Spring AI 2.0.1, Kotlin 2.3.21, Jackson 3 (tools.jackson), and gemini-3.5-flash-lite.


Prompt instructions vs. provider-native JSON Schema

Telling a model “respond with raw JSON only” in the prompt works most of the time, but “most of the time” still means writing retry loops and regex fence strippers in production. Even a single translated enum value (for example, "Intermediate" instead of "INTERMEDIATE") throws a deserialization exception.

Google Gemini supports response_mime_type: application/json together with response_schema. Under the hood, Gemini applies constrained decoding directly to the next-token logits so any token that violates the schema gets masked out before sampling.

flowchart TD
    DTO["Kotlin DTO and Enum definitions"] --> Extract["BeanOutputConverter generates JSON Schema"]
    Extract --> Inline["JsonSchemaInliner expands $defs and $ref"]
    Inline --> Opts["GoogleGenAiChatOptions (responseMimeType + responseSchema)"]
    Opts --> Gemini["Gemini constrained decoding"]
    Gemini --> Parse["Jackson deserialization (zero syntax retries)"]

Prompt-based .entity() vs. native responseSchema

DimensionPrompt-based ChatClient.entity()Native responseSchema + BeanOutputConverter
Schema enforcementSoft (format instructions appended to prompt)Hard (constrained decoding at token generation)
Markdown fence riskOccasional ( ``json ` wrappers)None (application/json output)
Enum strictnessCan drift or localize enum namesLocked to declared enum values
Prompt token overheadAdds full schema text to the promptSent as structured API option
Nested $ref handling in Spring AI 2.0.1Handled by prompt textDrops $defs/$ref unless inlined

When not to use native responseSchema: Avoid it when your DTO is recursive (such as a tree node referencing itself) or relies on complex polymorphic hierarchies (@JsonSubTypes with deep oneOf branches). Gemini’s schema subset doesn’t support unbounded recursive references, so you’ll need to flatten the DTO first or fall back to prompt-guided JSON with validation.


Project setup and nested DTO design

The full working module lives in spring-ai-examples (structured-output).

build.gradle.kts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
plugins {
    kotlin("jvm") version "2.3.21"
    kotlin("plugin.spring") version "2.3.21"
    id("org.springframework.boot") version "4.1.1"
    id("io.spring.dependency-management") version "1.1.7"
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.ai:spring-ai-starter-model-google-genai")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")

    testImplementation("org.springframework.boot:spring-boot-starter-test")
    testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
}

Nested DTOs and shared enums

To mirror a realistic payload, ReadingCuration contains a list of CuratedBook items, two enums (Level and Category), and a nested string list. Notice that Level is reused in both ReadingCuration.targetLevel and CuratedBook.level:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package io.github.cmsong111.structured_output.dto

data class ReadingCuration(
    val theme: String,
    val targetLevel: Level,
    val books: List<CuratedBook>,
    val curatorComment: String
)

data class CuratedBook(
    val title: String,
    val author: String,
    val publishedYear: Int,
    val level: Level,
    val category: Category,
    val keyTakeaways: List<String>
)

enum class Level {
    BEGINNER, INTERMEDIATE, ADVANCED
}

enum class Category {
    PROGRAMMING, ARCHITECTURE, CULTURE, ESSAY
}

Fixing the $defs and $ref bug with GeminiBeanOutputConverter

Passing BeanOutputConverter(ReadingCuration::class.java).jsonSchema directly to GoogleGenAiChatOptions hits a nasty edge case in Spring AI 2.0.1.

When the same type (like Level) appears more than once in a DTO graph, BeanOutputConverter emits JSON Schema $defs and points to it via $ref (#/$defs/Level). In Spring AI 2.0.1, GoogleGenAiChatModel converts the JSON string into Gemini SDK Schema objects without resolving $defs/$ref. Those fields silently lose their enum constraints, allowing the model to emit arbitrary strings.

To fix this, I subclassed BeanOutputConverter into GeminiBeanOutputConverter and added a small recursive JsonSchemaInliner that resolves every #/$defs/... reference inline and strips the $defs block before passing the schema to Gemini:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package io.github.cmsong111.structured_output.converter

import org.springframework.ai.converter.BeanOutputConverter
import tools.jackson.databind.JsonNode
import tools.jackson.databind.json.JsonMapper
import tools.jackson.databind.node.ArrayNode
import tools.jackson.databind.node.ObjectNode

class GeminiBeanOutputConverter<T : Any>(clazz: Class<T>) : BeanOutputConverter<T>(clazz) {

    private val inlinedSchema: String = JsonSchemaInliner.inline(super.getJsonSchema())

    override fun getJsonSchema(): String = inlinedSchema
}

object JsonSchemaInliner {
    private const val DEFS = "\$defs"
    private const val REF = "\$ref"
    private const val REF_PREFIX = "#/\$defs/"
    private val jsonMapper = JsonMapper.builder().build()

    fun inline(jsonSchema: String): String {
        val root = jsonMapper.readTree(jsonSchema) as ObjectNode
        val defs = root.get(DEFS) as? ObjectNode ?: return jsonSchema

        val inlined = resolve(root, defs, depth = 0) as ObjectNode
        inlined.remove(DEFS)
        return jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(inlined)
    }

    private fun resolve(node: JsonNode, defs: ObjectNode, depth: Int): JsonNode {
        check(depth < 32) { "Cannot inline recursive \$ref beyond depth 32." }
        return when (node) {
            is ObjectNode -> {
                val ref = node.get(REF)?.asString()
                val result: ObjectNode = if (ref != null && ref.startsWith(REF_PREFIX)) {
                    val target = defs.get(ref.removePrefix(REF_PREFIX))
                        ?: error("Schema definition not found: $ref")
                    resolve(target, defs, depth + 1).deepCopy() as ObjectNode
                } else {
                    jsonMapper.createObjectNode()
                }
                node.properties()
                    .filter { (key, _) -> key != REF }
                    .forEach { (key, value) -> result.set(key, resolve(value, defs, depth + 1)) }
                result
            }
            is ArrayNode -> jsonMapper.createArrayNode().apply {
                node.forEach { add(resolve(it, defs, depth + 1)) }
            }
            else -> node
        }
    }
}

The depth guard (depth < 32) prevents infinite recursion if someone accidentally passes a self-referential DTO. Running the inliner expands every $ref into a self-contained schema that Gemini’s SDK accepts cleanly:

Console diff showing JsonSchemaInliner resolving $ref and removing $defs Figure 1. JsonSchemaInliner debug output showing $ref and $defs fully expanded inline.


Implementing StructuredOutputService

In StructuredOutputService, I kept both the standard ChatClient .entity() path and the provider-native responseSchema path side by side so you can compare them directly:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package io.github.cmsong111.structured_output.service

import io.github.cmsong111.structured_output.converter.GeminiBeanOutputConverter
import io.github.cmsong111.structured_output.dto.ReadingCuration
import org.springframework.ai.chat.client.ChatClient
import org.springframework.ai.google.genai.GoogleGenAiChatOptions
import org.springframework.stereotype.Service

@Service
class StructuredOutputService(
    private val chatClient: ChatClient
) {
    private val curationConverter = GeminiBeanOutputConverter(ReadingCuration::class.java)

    /**
     * 1. Prompt-based ChatClient Fluent .entity() approach
     */
    fun curateWithPrompt(topic: String): ReadingCuration? {
        return chatClient.prompt()
            .system("You are a senior software engineering book curator.")
            .user("Recommend 3 books for this topic: '$topic'")
            .call()
            .entity(ReadingCuration::class.java)
    }

    /**
     * 2. Gemini provider-native responseSchema option
     */
    fun curateWithNativeSchema(topic: String): ReadingCuration? {
        val nativeOptions = GoogleGenAiChatOptions.builder()
            .responseMimeType("application/json")
            .responseSchema(curationConverter.jsonSchema)
            .build()

        val rawJson = chatClient.prompt()
            .options(nativeOptions)
            .system("You are a senior software engineering book curator.")
            .user("Recommend 3 books for this topic: '$topic'")
            .call()
            .content() ?: return null

        return curationConverter.convert(rawJson)
    }
}

Notice that curationConverter is instantiated once as a service field, so JsonSchemaInliner.inline(...) runs only once at startup instead of re-parsing the schema on every request.


Verification and test results

I tested both methods against live gemini-3.5-flash-lite calls using StructuredOutputIntegrationTests:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@SpringBootTest
class StructuredOutputIntegrationTests {

    @Autowired
    private lateinit var structuredOutputService: StructuredOutputService

    @Test
    fun `parses nested curation DTO from Gemini response`() {
        val topic = "Object-oriented design and refactoring"
        val curation = structuredOutputService.curateWithNativeSchema(topic)

        println("=== [StructuredOutput] Native Schema ===")
        println(curation)

        assertThat(curation).isNotNull
        assertThat(curation?.books).hasSize(3)
        assertThat(curation?.targetLevel).isNotNull()
    }
}

Integration test console

Integration test console output for Gemini structured output DTO deserialization Figure 2. JUnit 5 integration test passing with nested lists and strict enum values bound into ReadingCuration.

A single call deserializes cleanly into the Kotlin data class without retries or post-processing:

1
2
3
4
5
6
7
8
9
10
ReadingCuration(
  theme=Object-oriented design and refactoring,
  targetLevel=INTERMEDIATE,
  books=[
    CuratedBook(title=The Essence of Object-Orientation, author=Youngho Cho, publishedYear=2015, level=BEGINNER, category=PROGRAMMING),
    CuratedBook(title=Refactoring (2nd Edition), author=Martin Fowler, publishedYear=2018, level=INTERMEDIATE, category=PROGRAMMING),
    CuratedBook(title=Clean Architecture, author=Robert C. Martin, publishedYear=2017, level=ADVANCED, category=ARCHITECTURE)
  ],
  curatorComment=A progressive path from object-oriented fundamentals through refactoring to system architecture.
)

Verifying the REST endpoint with curl

Calling the exposed endpoint (GET /api/curation?topic=...) returns strict JSON matching the Kotlin DTO contract:

cURL response showing strict JSON matching the ReadingCuration DTO schema Figure 3. REST endpoint response returning schema-compliant JSON directly from Gemini.


Production caveats and checklist

Even with constrained decoding active, keep these practical limits in mind:

  • Schema guarantees syntax, not truth: Constrained decoding ensures publishedYear is an integer and category is a valid enum, but the model can still hallucinate a wrong publication year. Validate domain invariants separately if accuracy matters.
  • Avoid overly deep or wide schemas: Very large JSON schemas increase first-token latency and can trigger Gemini’s schema complexity limit (400 INVALID_ARGUMENT). Keep response DTOs focused on the fields your caller actually uses.
  • Cache the inlined schema: Build GeminiBeanOutputConverter once per DTO type rather than inside a per-request method.
  • Watch nullable vs. required fields: Add @JsonPropertyDescription on optional fields (see how I use it in parsing receipts and audio meetings with Spring AI and Gemini) so the model knows when null is acceptable instead of inventing placeholder strings.

Pre-deploy checklist

  • Use GoogleGenAiChatOptions with both responseMimeType("application/json") and responseSchema(...).
  • Wrap BeanOutputConverter with a $ref/$defs inliner whenever a DTO reuses enums or nested types.
  • Guard the inliner against recursive DTO definitions with a maximum depth check.
  • Reuse converter instances as singletons so schema generation and inlining happen once at startup.

The complete source code for this walkthrough is in cmsong111/spring-ai-examples/structured-output.

This post is licensed under CC BY 4.0 by the author.