Developer Documentation
C#
Updated September 19, 2026

Validate JSON in C#

Validate JSON syntax and handle parser errors without mutating the input in C#.

Syntax validation answers one question: can the input be parsed as JSON? It is different from JSON Schema validation, which checks the shape and constraints of already valid JSON data.

Quick Start#

The following example uses the standard C# API or a widely used package for this task.

Syntax validation#

C#
1using System.Text.Json;23try4{5    using JsonDocument doc = JsonDocument.Parse(input);6    Console.WriteLine("Valid JSON");7}8catch (JsonException ex)9{10    Console.WriteLine($"Invalid near line {ex.LineNumber}, byte {ex.BytePositionInLine}");11}

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

Validate expected fields#

C#
1using JsonDocument doc = JsonDocument.Parse(input);2JsonElement root = doc.RootElement;3if (root.ValueKind != JsonValueKind.Object ||4    !root.TryGetProperty("name", out JsonElement name) ||5    name.ValueKind != JsonValueKind.String)6{7    throw new InvalidDataException("name must be a string");8}

Important Notes#

Use a dedicated schema validator when you need full JSON Schema semantics; System.Text.Json itself focuses on parsing and serialization.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement JSON Validator in other languages: