Spring › Spring-AI

Enforcing JSON Schema structured output with Gemini API

Enforce strict JSON Schema output on gemini-3.5-flash-lite with Google GenAI SDK responseJsonSchema to eliminate retry costs and parse safely in Kotlin.

Enforcing JSON Schema structured output with Gemini API

Unstructured text and malformed JSON are the most common failure points when wiring an LLM into a backend batch pipeline. This post shows how I enforced a strict JSON Schema on gemini-3.5-flash-lite using the Google GenAI SDK’s responseJsonSchema, cut format retries to zero, and paired schema constraints with server-side domain validation in Kotlin.

Tested with Spring Boot 4.1.1, Spring AI 2.0.1, Google GenAI Java SDK, Kotlin 2.3, and gemini-3.5-flash-lite.


Why prompt instructions fail under batch load

In my court-ruling ingestion and summarization service (demo-backend-server), a scheduled batch job (judgment-discovery) collects recent news articles about court decisions through Google Search and turns them into structured candidate records.

To deserialize those candidates into Kotlin domain objects, the model had to return JSON matching a fixed contract. At first, I relied on prompt instructions alone:

1
2
Extract the case number, court name, sentencing date, and key issues from the search results below as a JSON array.
- Return raw JSON only. Do not wrap the response in markdown fences (```json) or add any preamble.

That looked fine in local smoke tests, but running hundreds of batch jobs in production exposed three recurring failures:

  1. Markdown fences and conversational chatter: Despite explicit instructions, the model intermittently wrapped output in ` json ... ` blocks or prepended a short explanation, breaking Jackson immediately.
  2. Missing fields and invented keys: The model sometimes emitted case_no instead of caseNumber, omitted nullable fields altogether, or returned free-form strings outside the allowed enum values (JUDGMENT, PRE_JUDGMENT).
  3. Retry latency and token waste: Every JsonParseException triggered an API retry. Because a single Gemini call takes several seconds, retries doubled or tripled batch duration while burning extra input and output tokens.

Regex stripping and defensive prompt wording only papered over the symptom. They couldn’t guarantee a clean parse on every run.


How Gemini constrained decoding enforces JSON Schema

The real fix happens at token generation time, not in post-processing. With Constrained Decoding, the inference engine compiles your JSON Schema into a grammar state machine before sampling begins. At each decoding step, any token that would violate the schema grammar has its logit masked to negative infinity (zero probability), so the model physically cannot emit invalid syntax.

The Google Gemini API exposes this through GenerateContentConfig using responseMimeType and responseJsonSchema:

flowchart TD
    P["DiscoveryPrompts.structure()"] -->|"Prompt text"| CD["Gemini Constrained Decoding\n(gemini-3.5-flash-lite)"]
    S["JSON Schema Map\n(DiscoveryPrompts.schema)"] -->|"responseJsonSchema"| CD
    CD -->|"100% schema-valid JSON"| J["Jackson JsonMapper\n(Zero-Retry Parsing)"]
    J --> R["DiscoveryRules.check()\n(Server-Side Ground Truth)"]

Because the decoder enforces the schema at the token level, markdown fences, comments, and preamble text cannot be generated. Every response that finishes with STOP is guaranteed to match the declared keys, types, and enums.

Gemini Response Schema builder debug console in IntelliJ Figure 1. Inspecting GenerateContentConfig and the responseJsonSchema payload inside the IntelliJ debugger.


Building a strict JSON Schema and calling the SDK

In demo-backend-server, I keep prompt versioning and schema construction together in a single Kotlin object (DiscoveryPrompts). Building the schema with plain Kotlin maps avoids extra schema-generation dependencies and makes every constraint explicit in code review:

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
// src/main/kotlin/com/example/server/discovery/application/DiscoveryPrompts.kt
package com.example.server.discovery.application

object DiscoveryPrompts {
    const val VERSION = "discovery-v2"

    fun schema(maxCandidates: Int): Map<String, Any> {
        val nullableString = mapOf("type" to listOf("string", "null"))
        val candidate = mapOf(
            "type" to "object",
            "properties" to mapOf(
                "stage" to mapOf("type" to "string", "enum" to listOf("JUDGMENT", "PRE_JUDGMENT")),
                "title" to mapOf("type" to "string"),
                "issueSummary" to mapOf("type" to "string"),
                "issueEvidence" to mapOf("type" to "string"),
                "caseNumber" to nullableString,
                "courtName" to nullableString,
                "sentenceDate" to nullableString,
                "instance" to mapOf("type" to "string", "enum" to listOf("FIRST", "APPEAL", "SUPREME", "UNKNOWN")),
                "sources" to mapOf("type" to "array", "items" to mapOf(
                    "type" to "object",
                    "properties" to mapOf("id" to mapOf("type" to "string"), "reportedDate" to nullableString),
                    "required" to listOf("id", "reportedDate"),
                )),
            ),
            "required" to listOf(
                "stage", "title", "issueSummary", "issueEvidence",
                "caseNumber", "courtName", "sentenceDate", "instance", "sources"
            ),
        )
        return mapOf(
            "type" to "object",
            "properties" to mapOf(
                "candidates" to mapOf("type" to "array", "maxItems" to maxCandidates, "items" to candidate)
            ),
            "required" to listOf("candidates"),
        )
    }
}

Three schema choices mattered most in practice:

  • Explicit nullable types: News articles often omit the exact case number or sentencing date. Declaring "type" to listOf("string", "null") lets the model emit null cleanly instead of guessing or writing "N/A".
  • Strict enums: Locking stage and instance to exact enum values eliminates IllegalArgumentException during domain mapping.
  • Exhaustive required lists: Listing every property in required forces the model to emit explicit null values rather than dropping keys silently.

Calling the Google GenAI SDK directly

In Spring AI 2.0.1, ChatResponse doesn’t preserve the full groundingMetadata returned from Google Search grounding (which I cover in my post on Gemini Search Grounding and comparing Spring AI with the GenAI SDK). Because this pipeline already calls com.google.genai.Client directly for the search step, I used the same SDK client for the structured extraction step:

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
// src/main/kotlin/com/example/server/discovery/application/DiscoveryModel.kt
package com.example.server.discovery.application

import com.google.genai.Client
import com.google.genai.types.GenerateContentConfig
import com.google.genai.types.GenerateContentResponse
import com.example.server.discovery.JudgmentDiscoveryProperties

data class DiscoveryStructureResult(val json: String, val usage: DiscoveryUsage?)

class GeminiDiscoveryModel(
    private val client: Client,
    private val properties: JudgmentDiscoveryProperties
) : DiscoveryModel {

    override fun structure(prompt: String, schema: Map<String, Any>): DiscoveryStructureResult {
        val config = GenerateContentConfig.builder()
            .responseMimeType("application/json")
            .responseJsonSchema(schema)
            .maxOutputTokens(properties.maxOutputTokens)
            .build()
        val response = call { client.models.generateContent(properties.model, prompt, config) }
        return DiscoveryStructureResult(text(response), usage(response))
    }

    private fun text(response: GenerateContentResponse): String {
        val candidate = response.candidates().orElse(emptyList()).firstOrNull()
        val finish = candidate?.finishReason()?.orElse(null)?.toString()
        val text = candidate?.content()?.orElse(null)?.parts()?.orElse(emptyList()).orEmpty()
            .filter { it.thought().orElse(false) != true }
            .mapNotNull { it.text().orElse(null) }
            .joinToString("").trim()

        if (finish != null && finish != "STOP") throw DiscoveryModelException("Gemini response did not finish cleanly: $finish")
        if (text.isEmpty()) throw DiscoveryModelException("Gemini response body is empty.")
        return text
    }
}

Notice the finish != "STOP" guard and the thought part filter. Even with constrained decoding, a response that hits MAX_TOKENS gets cut off mid-object, producing truncated JSON. Checking finishReason before parsing turns a confusing Jackson EOF error into an explicit capacity error.


Zero-retry deserialization and Flash-Lite cost benchmarks

Once responseJsonSchema is active, the batch consumer parses the response straight through Jackson without regex cleanup or retry loops:

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
// src/main/kotlin/com/example/server/discovery/application/JudgmentDiscoveryJobs.kt
val (structured, record) = call(context.runId, DiscoveryCallStage.STRUCTURE, { it.usage }) {
    model.structure(
        DiscoveryPrompts.structure(search.text, search.sources, from, to, properties.maxCandidates),
        DiscoveryPrompts.schema(properties.maxCandidates)
    )
}

// Parse directly without regex trimming because the decoder enforces the schema
val nodes = try {
    mapper.readTree(structured.json)?.path("candidates")?.takeIf { it.isArray }?.toList()
} catch (e: tools.jackson.core.JacksonException) {
    null
}

if (nodes == null) {
    record.succeeded = false
    record.error = "Structured response did not match the expected JSON schema; candidates were not saved."
    calls.save(record)
    throw IllegalStateException(record.error)
}

// Validate each parsed node against server-side business rules
for (node in nodes.take(properties.maxCandidates)) {
    when (val result = DiscoveryRules.check(node, search, from, to)) {
        is CandidateCheck.Accepted -> service.upsert(result.candidate, context.runId, model.modelName, DiscoveryPrompts.VERSION)
        is CandidateCheck.PreJudgment -> context.skip()
        is CandidateCheck.Rejected -> context.failure("discovery:${result.title.take(80)}", result.reason)
    }
}

Spring Boot batch console showing zero-retry strict JSON parsing Figure 2. Spring Boot batch log showing clean JSON deserialization with zero retries.

Pairing strict schemas with gemini-3.5-flash-lite

The biggest payoff wasn’t just removing retry code—it was unlocking a much smaller model. Under free-form prompting, smaller models drift off-format more often, which pushed me toward gemini-2.5-pro. Under constrained decoding, format drift drops to 0% regardless of model size, so gemini-3.5-flash-lite became viable for structured extraction.

Token usage and latency benchmark comparing Pro and Flash-Lite Figure 3. Format integrity, latency, output tokens, and monthly cost comparing Pro with free-form prompting against Flash-Lite with a strict schema.

Here are the production metrics I measured across the batch workload:

Metricgemini-2.5-pro (Prompt-only)gemini-3.5-flash-lite (Strict Schema)Delta
Format error / retry rate4.8 %0.0 %Retries eliminated
Median latency (p50)5,820 ms1,103 ms~81% faster
Average output tokens1,840 tokens680 tokens63% fewer tokens
Monthly cost (1,000 runs)$8.40 USD$0.48 USD~94.3% cheaper

Cutting out narrative filler reduced output tokens by 63%, and moving to flash-lite cut monthly batch spend by roughly 20x.

When not to use strict JSON Schema

Constrained decoding isn’t the right fit for every call:

  • Deeply nested or recursive schemas: Gemini’s grammar compiler enforces state limits. Schemas with heavy nesting, recursive $ref definitions, or dozens of optional branches can fail at request time with a schema-too-complex error.
  • Open-ended reasoning before classification: Forcing a tiny model straight into a bare enum field without a preceding issueEvidence or reasoning field can hurt accuracy. Give the model a short evidence field before the classification field, or split reasoning and formatting into two calls.
  • User-facing streaming prose: If you’re streaming conversational tokens to a UI via SSE, raw JSON tokens are awkward to render incrementally compared to plain markdown text.

Second line of defense: server-side business rules

JSON Schema guarantees structural validity, not factual accuracy (ground truth). A schema-valid response can still fabricate a plausible case number or cite a source ID that doesn’t exist in the search results.

Right after parsing, every candidate passes through deterministic server-side rules in DiscoveryRules.check:

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
// src/main/kotlin/com/example/server/discovery/application/DiscoveryRules.kt
object DiscoveryRules {
    // Korean court case number pattern: 2-4 digits + 1-4 Hangul characters + 1-7 digits
    private val CASE_NUMBER = Regex("^\\d{2,4}[\\uAC00-\\uD7A3]{1,4}\\d{1,7}$")
    private val SOURCE_ID = Regex("^S(\\d{1,3})$")

    fun check(node: JsonNode, search: DiscoverySearchResult, from: LocalDate, to: LocalDate): CandidateCheck {
        val title = text(node, "title")?.take(200)
            ?: return CandidateCheck.Rejected("(untitled)", "Candidate title is missing.")
        if (text(node, "stage") == "PRE_JUDGMENT") return CandidateCheck.PreJudgment(title)
        if (text(node, "stage") != "JUDGMENT") return CandidateCheck.Rejected(title, "Invalid judgment stage value.")

        // Source verification: accept only source IDs (S1..Sn) that exist in the grounding list
        val sources = node.path("sources").takeIf { it.isArray }?.toList().orEmpty().mapNotNull { item ->
            val index = SOURCE_ID.matchEntire(text(item, "id").orEmpty())?.groupValues?.get(1)?.toInt()
            index?.let { search.sources.getOrNull(it - 1) }?.let { SourceInput(it, domain(it), date(text(item, "reportedDate"))) }
        }.distinctBy { it.source.url }

        if (sources.isEmpty()) return CandidateCheck.Rejected(title, "Candidate has no verified source from the search response.")

        // Case number verification: must match format AND appear verbatim in the search text
        val caseNumber = text(node, "caseNumber")?.let(::compact)?.takeIf {
            CASE_NUMBER.matches(it) && bounded(it, search.text)
        }

        // Court name normalization: map abbreviations to canonical court names
        val courtName = text(node, "courtName")?.let { court(it, compact(search.text)) }

        return CandidateCheck.Accepted(
            CandidateInput(
                title = title,
                issueSummary = text(node, "issueSummary")!!,
                issueEvidence = text(node, "issueEvidence"),
                caseNumber = caseNumber,
                courtName = courtName,
                sentenceDate = date(text(node, "sentenceDate")),
                instance = DiscoveryInstance.valueOf(text(node, "instance") ?: "UNKNOWN"),
                recency = DiscoveryRecency.RECENT_SENTENCE,
                sources = sources,
                notes = emptyList()
            )
        )
    }
}

This creates a two-tier safety boundary: JSON Schema enforces syntax and types at the model decoder, while server rules enforce domain invariants and cross-check extracted facts against the original search payload.


Production caveats and checklist

Always check finishReason == "STOP" before calling Jackson. If maxOutputTokens is too tight for maxCandidates, Gemini truncates the JSON mid-stream and constrained decoding won’t save you from a parse failure.

Before shipping structured outputs to production, run through this checklist:

  • Set both responseMimeType("application/json") and responseJsonSchema(schema) on GenerateContentConfig.
  • Mark optional fields as ["string", "null"] and list every property under required so keys aren’t silently omitted.
  • Guard against MAX_TOKENS and SAFETY finish reasons before deserializing, and filter out thought parts when using thinking-capable models.
  • Pair schema enforcement with server-side cross-checks (regex format, enum mapping, and source ID verification) to catch factual hallucinations.

References

  • Learn how to generate structured JSON output with the Gemini API.

</div>

</div>

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