Data and Formats · Lesson 5

Malformed JSON

Handle syntax errors at the import boundary.

How it works

Malformed JSON cannot be decoded into the requested data model, so JsonSerializer reports a JsonException. This catch turns that expected import failure into a clear result while leaving unrelated exceptions visible. Syntax validity is only the first stage: a syntactically valid array can still violate limits on length or allowed values. Avoid displaying raw exception text as a permanent user-facing format because it may change across runtime versions or contain input details.

Preserve useful diagnostics for development, and present a stable message that tells the person how to repair the document they supplied.

Replace the input with an empty array and with an array containing negative values. Explain which inputs are valid JSON and which additional domain rules would need a separate validation step.

A working example

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

try { JsonSerializer.Deserialize<int[]>("[1,broken]"); }
catch (JsonException) { Console.WriteLine("Invalid JSON"); }

Expected output

Invalid JSON
Try this
Catch format errors where the import can show an actionable result.