Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

JsonException — JSON data errors

JsonException from System.Text.Json signals invalid JSON, an exceeded nesting limit, or a value incompatible with the target type. It also exposes diagnostic information that helps locate the problem in the input.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

catch (JsonException ex) { /* handle invalid JSON data */ }
throw new JsonException("Invalid JSON value.");

JsonException is an exception class in the System.Text.Json namespace that inherits from Exception. It is available in .NET 10; it is not a new C# language feature. It signals invalid JSON syntax, an exceeded maximum depth, or data incompatible with the target type. Valid JSON syntax therefore does not guarantee successful deserialization.

Path identifies the problem location within the JSON structure. LineNumber and BytePositionInLine are zero-based and have type long?, so they may have no value. BytePositionInLine counts UTF-8 bytes, not characters. Message describes the error; avoid comparing the entire library-generated message in tests.

In a custom converter, use throw new JsonException("Invalid JSON value."); to reject an unacceptable value. During deserialization, the serializer can populate Path, LineNumber, and BytePositionInLine, even when you supply your own message. If the converter throws while writing JSON, the serializer can populate Path while leaving LineNumber and BytePositionInLine unset. The constructor accepting a message and an inner exception lets you preserve the underlying cause.

Catch JsonException around a read operation whose failure you can handle; do not silently swallow it. In the example, "oops" is a valid JSON string but is incompatible with the int property Age. The program prints a fixed message and the path $.Age rather than an environment-dependent error description.

Examples

using System;
using System.Text.Json;

internal static class Program
{
    private static void Main()
    {
        const string json = "{\"Age\":\"oops\"}";

        try
        {
            JsonSerializer.Deserialize<Person>(json);
            Console.WriteLine("Accepted");
        }
        catch (JsonException ex)
        {
            Console.WriteLine("Rejected JSON value");
            Console.WriteLine($"Path: {ex.Path}");
        }
    }
}

public sealed class Person
{
    public int Age { get; set; }
}

Result

Rejected JSON value
Path: $.Age

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources