spring-projects/spring-ai · error · RuntimeException
Failed to parse JSON:
Error message
Failed to parse JSON:
What it means
JsonSchemaConverter.fromJson(jsonString) parses a JSON string into a Jackson ObjectNode using the shared mapper; any parse/IO exception is rethrown as a RuntimeException with the offending string in the message. The library throws this when the supplied text is not valid JSON.
Source
Thrown at models/spring-ai-google-genai/src/main/java/org/springframework/ai/google/genai/schema/JsonSchemaConverter.java:54
*/
public final class JsonSchemaConverter {
private JsonSchemaConverter() {
// Prevent instantiation
}
/**
* Parses a JSON string into an ObjectNode.
* @param jsonString The JSON string to parse
* @return ObjectNode containing the parsed JSON
* @throws RuntimeException if the JSON string cannot be parsed
*/
public static ObjectNode fromJson(String jsonString) {
try {
return (ObjectNode) JacksonUtils.getDefaultJsonMapper().readTree(jsonString);
}
catch (Exception e) {
throw new RuntimeException("Failed to parse JSON: " + jsonString, e);
}
}
/**
* Converts a JSON Schema ObjectNode to OpenAPI schema format.
* @param jsonSchemaNode The input JSON Schema as ObjectNode
* @return ObjectNode containing the OpenAPI schema
* @throws IllegalArgumentException if jsonSchemaNode is null
*/
public static ObjectNode convertToOpenApiSchema(ObjectNode jsonSchemaNode) {
Assert.notNull(jsonSchemaNode, "JSON Schema node must not be null");
Assert.isTrue(!jsonSchemaNode.has("$defs"), "Google's Structured Output schema doesn't support $defs property");
try {
// Convert to OpenAPI schema using our custom conversion logic
ObjectNode openApiSchema = convertSchema(jsonSchemaNode,
JacksonUtils.getDefaultJsonMapper().getNodeFactory());
View on GitHub (pinned to 98a7beda4f)
Solutions
- Validate the JSON string with a linter/parser before passing it in
- Trim whitespace and remove non-JSON prefixes/suffixes (e.g., markdown fences from LLM output)
- Confirm the string is not empty or truncated
- Catch RuntimeException and surface the failing input for debugging
Example fix
// before
ObjectNode schema = JsonSchemaConverter.fromJson(raw);
// after
String cleaned = raw.strip().replaceAll("^```(json)?|```$", "");
ObjectNode schema = JsonSchemaConverter.fromJson(cleaned); Defensive patterns
Strategy: validation
Validate before calling
if (json == null || json.isBlank()) {
throw new IllegalArgumentException("empty JSON input");
}
try (var p = new java.io.StringReader(json)) {
new com.fasterxml.jackson.core.JsonFactory().createParser(p).close(); // cheap syntax probe
} Type guard
boolean isProbablyJson(String s) {
if (s == null) return false;
String t = s.strip();
return (t.startsWith("{") && t.endsWith("}")) || (t.startsWith("[") && t.endsWith("]"));
} Try / catch
try {
ObjectNode node = JsonSchemaConverter.fromJson(json);
} catch (RuntimeException e) {
logger.error("bad schema input: {}", e.getMessage());
throw new IllegalArgumentException("schema must be valid JSON", e);
} Prevention
- Strip markdown code fences from LLM-emitted schemas
- Lint JSON schemas in CI before shipping them
- Check inputs are not empty or truncated
- Keep schemas as resource files and validate at build time
When it happens
Trigger: Calling fromJson with malformed JSON, empty/blank input, or JSON that fails to read (e.g., trailing garbage, unquoted keys).
Common situations: Hand-written JSON Schemas pasted into code, schemas read from files/LLM output with stray text, or truncation of large schema strings.
Understand the failure class
Background: JSON parse error: "Unexpected token" / "not valid JSON" / "failed to parse" — what JSON parsers are really complaining about — this error's family across 45 libraries.
- Parsing and encoding errors: unexpected token, malformed input — why parsers reject input and how to find the real culprit.
Related errors
- JacksonException (wrapped IllegalStateException)
- Error parsing JSON-RPC message:
- Failed to parse JSON:
- Cannot deserialize ThinkOption from token:
- Failed to parse JSON schema
AI-assisted analysis of spring-projects/spring-ai@98a7beda4f (2026-09-11).
Data as JSON: /api/errors/3f109b3e7193d88d.
Report an issue: GitHub.