{"record":{"id":"750de0e83fd58ce6","repo":"google/gson","slug":"message-locationstring-see-troubleshootin","errorCode":null,"errorMessage":"${message}${locationString()}\nSee ${TroubleshootingGuide.createUrl(\"malformed-json\")}","messagePattern":"\\$\\{message\\}\\$\\{locationString\\(\\)\\}\nSee \\$\\{TroubleshootingGuide\\.createUrl\\(\"malformed-json\"\\)\\}","errorType":"exception","errorClass":"MalformedJsonException","httpStatus":null,"severity":"error","filePath":"gson/src/main/java/com/google/gson/stream/JsonReader.java","lineNumber":1840,"sourceCode":"        if (strictness == Strictness.STRICT) {\n          throw syntaxError(\"Invalid escaped character \\\"'\\\" in strict mode\");\n        }\n      case '\"':\n      case '\\\\':\n      case '/':\n        return escaped;\n      default:\n        // throw error when none of the above cases are matched\n        throw syntaxError(\"Invalid escape sequence\");\n    }\n  }\n\n  /**\n   * Throws a new {@link MalformedJsonException} with the given message and information about the\n   * current location.\n   */\n  private MalformedJsonException syntaxError(String message) throws MalformedJsonException {\n    throw new MalformedJsonException(\n        message + locationString() + \"\\nSee \" + TroubleshootingGuide.createUrl(\"malformed-json\"));\n  }\n\n  private IllegalStateException unexpectedTokenError(String expected) throws IOException {\n    JsonToken peeked = peek();\n    String troubleshootingId =\n        peeked == JsonToken.NULL ? \"adapter-not-null-safe\" : \"unexpected-json-structure\";\n    return new IllegalStateException(\n        \"Expected \"\n            + expected\n            + \" but was \"\n            + peek()\n            + locationString()\n            + \"\\nSee \"\n            + TroubleshootingGuide.createUrl(troubleshootingId));\n  }\n\n  /** Consumes the non-execute prefix if it exists. */","sourceCodeStart":1822,"sourceCodeEnd":1858,"githubUrl":"https://github.com/google/gson/blob/310ac341f2f92a454b229bf21f70d2d18b2b6db7/gson/src/main/java/com/google/gson/stream/JsonReader.java#L1822-L1858","documentation":"Thrown by JsonReader.syntaxError() as a com.google.gson.stream.MalformedJsonException (an IOException subclass). It is the single funnel for ~21 distinct syntax violations in the reader (unterminated array/object/string/escape/comment, 'Expected name', 'Expected :', 'Expected value', 'Unexpected value', 'JSON forbids NaN and infinities', 'Malformed Unicode escape', 'Invalid escape sequence', 'Cannot escape a newline character in strict mode', 'Invalid escaped character in strict mode', 'String contains non-ASCII characters'). The message is composed as the specific reason plus a location string ('at line L column C path $...') and a troubleshooting URL. The exception is raised at JsonReader.java:1840-1841.","triggerScenarios":"Calling any JsonReader consuming method (peek, nextString, nextBoolean, nextDouble, nextLong, nextName, skipValue, or Gson.fromJson via the reader) on input that violates RFC 8259; unterminated literals; stray characters between tokens; single quotes or unquoted names when strictness is STRICT/LEGACY_STRICT; a missing colon after a name; a trailing comma in strict mode; an embedded NaN/Infinity literal; a \\uXXXX sequence with non-hex digits; a raw newline or apostrophe escaped only in STRICT mode.","commonSituations":"Reading JSON produced by a lenient writer or another language's serializer that emits comments, single-quoted strings, unquoted keys, or trailing commas; truncated network responses or partial file reads (unterminated structures); BOM or non-ASCII bytes in a stream decoded as the wrong charset; version mismatch where input previously tolerated under old lenient defaults now fails because Gson tightened defaults to LEGACY_STRICT; copy-pasting JSON with smart quotes or trailing punctuation.","solutions":["Inspect the reported line/column/path in the message to locate the offending byte, then fix the source data at that position.","Validate the input with a strict JSON parser or jsonlint before feeding it to Gson to get a clearer error.","If the input uses lenient syntax (comments, single quotes, unquoted keys, multiple top-level values), set reader.setStrictness(Strictness.LENIENT) before reading.","For truncated streams, ensure the producer writes complete JSON and the transport does not cut off mid-document; read fully into memory before parsing if partial reads are possible.","If you cannot change the data, switch to a tolerant reader or pre-process (strip comments, normalize quotes) before parsing."],"exampleFix":"// before\nJsonReader r = new JsonReader(new StringReader(\"{'k': 1,}\")); // single quotes + trailing comma\nr.beginObject(); // throws MalformedJsonException: ... See ...#malformed-json\n\n// after (accept lenient input)\nJsonReader r = new JsonReader(new StringReader(\"{'k': 1,}\"));\nr.setStrictness(Strictness.LENIENT);\nr.beginObject();","handlingStrategy":"try-catch","validationCode":"// Pre-validate the payload with a strict parser before handing to Gson.\n// Using javax.json (Jakarta JSON-P) as an independent validator:\nimport javax.json.Json;\nimport javax.json.JsonReader;\n// returns normally if valid, throws on malformed input\nvoid validateStrict(String payload) {\n  try (JsonReader r = Json.createReader(new StringReader(payload))) {\n    r.read(); // throws JsonParsingException on any syntax error\n  }\n}","typeGuard":"null","tryCatchPattern":"try {\n  T obj = gson.fromJson(payload, type);\n} catch (com.google.gson.JsonSyntaxException e) {\n  // Gson wraps MalformedJsonException in JsonSyntaxException when using Gson.fromJson(...)\n  Throwable cause = e.getCause();\n  if (cause instanceof com.google.gson.stream.MalformedJsonException) {\n    // message already contains line/column/path and a troubleshooting URL\n    log.warn(\"Malformed JSON rejected: {}\", cause.getMessage());\n  }\n  throw e;\n}\n\n// When using JsonReader directly:\ntry (JsonReader r = new JsonReader(reader)) {\n  r.setStrictness(Strictness.STRICT);\n  // ... consume ...\n} catch (com.google.gson.stream.MalformedJsonException e) {\n  // e.getMessage() ends with 'See https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json'\n  throw new InvalidPayloadException(\"Bad JSON input: \" + e.getMessage(), e);\n}","preventionTips":["Set reader strictness explicitly at construction so behavior does not depend on Gson defaults that change between versions.","Validate external/untrusted JSON with a strict parser or schema before deserialization.","Capture the line/column/path from the exception message to pinpoint the data error.","When streaming from network, fully buffer and boundary-check before parsing to avoid truncated-input failures.","If producers emit lenient dialects (comments, single quotes), agree on Strictness.LENIENT at both ends and document it."],"tags":["json","gson","parsing","malformed-json","strictness","java"],"backgroundTag":null,"analyzedSha":"310ac341f2f92a454b229bf21f70d2d18b2b6db7","analyzedAt":"2026-08-10T02:58:47.455Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}