{"record":{"id":"504ffbaea0e05491","repo":"elsa-workflows/elsa-core","slug":"failed-to-parse-jsondocument","errorCode":null,"errorMessage":"Failed to parse JsonDocument","messagePattern":"Failed to parse JsonDocument","errorType":"exception","errorClass":"JsonException","httpStatus":null,"severity":"error","filePath":"src/modules/Elsa.Workflows.Core/Activities/Flowchart/Serialization/ConnectionJsonConverter.cs","lineNumber":22,"sourceCode":"using Microsoft.Extensions.Logging;\n\nnamespace Elsa.Workflows.Activities.Flowchart.Serialization;\n\n/// <summary>\n/// Converts <see cref=\"Connection\"/> to and from JSON.\n/// </summary>\npublic class ConnectionJsonConverter(IDictionary<string, IActivity> activities, ILoggerFactory loggerFactory) : JsonConverter<Connection?>\n{\n    private readonly ILogger _logger = loggerFactory.CreateLogger<ConnectionJsonConverter>();\n\n    /// <inheritdoc />\n    public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(Connection);\n\n    /// <inheritdoc />\n    public override Connection? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n    {\n        if (!JsonDocument.TryParseValue(ref reader, out var doc))\n            throw new JsonException(\"Failed to parse JsonDocument\");\n\n        var root = doc.RootElement;\n\n        // case‐insensitive get\n        JsonElement Get(string name)\n        {\n            if (root.TryGetProperty(name, out var e))\n                return e;\n            var alt = char.ToUpperInvariant(name[0]) + name.Substring(1);\n            if (root.TryGetProperty(alt, out e))\n                return e;\n            throw new JsonException($\"Missing property '{name}' or '{alt}'\");\n        }\n\n        var sourceElement = Get(\"source\");\n        var targetElement = Get(\"target\");\n\n        // now inside sourceElement and targetElement, their children","sourceCodeStart":4,"sourceCodeEnd":40,"githubUrl":"https://github.com/elsa-workflows/elsa-core/blob/fe9217bdfa0e27f0e09e45006eb6898f616e513d/src/modules/Elsa.Workflows.Core/Activities/Flowchart/Serialization/ConnectionJsonConverter.cs#L4-L40","documentation":"Thrown in ConnectionJsonConverter.Read when JsonDocument.TryParseValue cannot parse the incoming token into a JsonDocument while deserializing a Flowchart Connection. It signals malformed JSON, not a missing field. Thrown during workflow definition deserialization.","triggerScenarios":"Deserializing workflow definitions where the JSON for a Connection element is syntactically invalid — truncated JSON, a bare string, or a non-object token where a connection object was expected.","commonSituations":"Corrupted workflow definition JSON stored in a database or file; hand-edited JSON; middleware that mangles the payload; truncated HTTP bodies.","solutions":["Validate the workflow definition JSON with JsonDocument.Parse before deserialization.","Check the JSON source (DB column, file, HTTP body) for truncation or encoding corruption.","Ensure each connection is a JSON object like {\"source\":..., \"target\":...}, not a string or array.","Wrap deserialization in try/catch for JsonException and log the raw JSON fragment to locate the corrupt element."],"exampleFix":"// before\nvar connection = JsonSerializer.Deserialize<Connection>(badJson); // throws JsonException\n// after\ntry { var connection = JsonSerializer.Deserialize<Connection>(json); }\ncatch (JsonException ex) { logger.LogError(ex, \"Invalid connection JSON: {Json}\", json); }","handlingStrategy":"try-catch","validationCode":"using var doc = JsonDocument.Parse(json); // throws early with position info if malformed","typeGuard":"static bool IsValidJson(string json) { try { using var _ = JsonDocument.Parse(json); return true; } catch (JsonException) { return false; } }","tryCatchPattern":"try { var connection = JsonSerializer.Deserialize<Connection>(json); }\ncatch (JsonException ex)\n{\n    logger.LogError(ex, \"Failed to deserialize Connection: {Message}\", ex.Message);\n}","preventionTips":["Validate stored workflow definition JSON after export/import round-trips.","Avoid hand-editing workflow JSON; use the designer or API.","Check DB columns/HTTP bodies for truncation before deserialization."],"tags":["json","serialization","flowchart","deserialization"],"backgroundTag":"json-parse-error","analyzedSha":"fe9217bdfa0e27f0e09e45006eb6898f616e513d","analyzedAt":"2026-09-13T20:32:34.702Z","contentChangedAt":"2026-09-13T20:32:34.702Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}