Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

System.Text.Json: The JSON value could not be converted to a type

The serializer refuses to coerce. Read the exception path, then add a converter for dates, number handling for quoted values, or an enum converter.

~4 min readC#
#C##.NET#JSON#Serialization
A json payload plate entering a converter socket blocked by an amber shape, a cyan converter gear fitted

Introduction & Quick Summary

System.Text.Json.JsonException: The JSON value could not be converted to System.DateTime. Path: $.createdAt | LineNumber: 0 | BytePositionInLine: 34 is the deserializer refusing to guess. System.Text.Json is strict by design: a number will not become a string, a string will not become a number, an enum name will not become an enum, and a date must be in a format it recognises. Where Newtonsoft.Json silently coerced, the built-in serializer throws.

The path and the byte position are the useful part: they say exactly which property failed, not just which type. The usual causes:

  • A date in a non-ISO format. 2026-11-21 10:00:00 fails; 2026-11-21T10:00:00Z parses.
  • A number sent as a string. "quantity": "5" needs JsonNumberHandling.AllowReadingFromString or a converter.
  • An enum sent by name. Without JsonStringEnumConverter, "status": "Active" fails against an enum.
  • A property name in a different case. By default matching is case-sensitive; createdAt does not bind to CreatedAt unless you relax it.
  • A type with no usable constructor. Positional records work; a class with only a parameterised constructor needs [JsonConstructor].
Message fragmentCauseFix
could not be converted to System.DateTimeNon-ISO date stringCustom JsonConverter<DateTime>
could not be converted to System.Int32Number sent as string, or a decimalJsonNumberHandling.AllowReadingFromString
could not be converted to MyEnumEnum name in the payloadJsonStringEnumConverter
could not be converted to System.StringNumber or object where a string is expectedMatch the contract, or use JsonElement
The JSON value is not in a supported formatTrailing content or malformed inputValidate the raw body first

Core Mechanics, Signatures & Reproducible Setup

Deserialization walks the JSON token by token and hands each value to the converter registered for the target property type. Built-in converters cover primitives, DateTime and DateTimeOffset in ISO 8601, TimeSpan in the constant format, Guid, and enums as numbers. Anything else either needs a converter or fails with this exception.

Two settings change behaviour globally. JsonSerializerOptions.PropertyNameCaseInsensitive matches names regardless of case, and JsonNumberHandling.AllowReadingFromString lets numeric properties accept quoted numbers. Enums need Converters.Add(new JsonStringEnumConverter()), and a custom date format needs a converter class.

A minimal reproduction reads a payload with an unquoted date format:

csharp
using System.Text.Json; public sealed record Order(string Id, DateTime CreatedAt, int Quantity); var json = """ { "id": "A-1", "createdAt": "2026-11-21 10:00:00", "quantity": "5" } """; var order = JsonSerializer.Deserialize<Order>(json); // throws on createdAt

The exception names the first failing property:

text
System.Text.Json.JsonException: The JSON value could not be converted to System.DateTime. Path: $.createdAt | LineNumber: 0 | BytePositionInLine: 45. ---> System.FormatException: The JSON value is not in a supported DateTime format.

Key Comparison Table

Choosing between a global option and a converter is the main design decision, because options apply to everything and converters are local.

NeedSettingScopeRisk
Quoted numbersJsonNumberHandling.AllowReadingFromStringOptionsHides contract drift
Case-insensitive namesPropertyNameCaseInsensitive = trueOptionsMasks naming bugs
Enum namesJsonStringEnumConverterOptionsNumeric payloads stop binding unless allowIntegerValues: true
Non-ISO datesCustom JsonConverter<T>Property or typeExtra code to maintain
Legacy payloadsJsonElement or JsonNodePropertyLoses type safety

The same failures also differ by runtime: .NET 6 is strict and case-sensitive, .NET 7 adds JsonNumberHandling, .NET 8 enables source generation by default in minimal APIs, and .NET 9 ships the JsonSerializerOptions.Web preset.

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

Dates: accept what your own API emits

A custom converter handles both the space-separated format and ISO, and fails loudly for anything else:

csharp
using System.Globalization; using System.Text.Json; using System.Text.Json.Serialization; public sealed class FlexibleDateTimeConverter : JsonConverter<DateTime> { private static readonly string[] Formats = { "yyyy-MM-dd'T'HH:mm:ssK", "yyyy-MM-dd'T'HH:mm:ss.FFFFFFFK", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd", }; public override DateTime Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options) { var text = reader.GetString(); if (DateTime.TryParseExact(text, Formats, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var value)) { return value; } throw new JsonException($"Unsupported date format: {text}"); } public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) => writer.WriteStringValue(value.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture)); }

Register it on the property with [JsonConverter(typeof(FlexibleDateTimeConverter))], or globally through options.Converters. Normalising the writer to "O" stops the problem returning: a serializer that emits "2026-11-21 10:00:00" creates a payload its own reader rejects.

Numbers sent as strings

Some APIs quote numbers to avoid JavaScript precision loss. The global option is the smallest change:

csharp
var options = new JsonSerializerOptions { NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.AllowNamedFloatingPointLiterals, PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, }; var order = JsonSerializer.Deserialize<Order>(json, options);

For a single awkward property, a property-scoped converter beats a project-wide relaxation: it documents which fields are irregular.

Enums and the string/number switch

JsonStringEnumConverter reads names and, since .NET 6, can also read numbers when constructed with allowIntegerValues: true. Without that flag, a numeric payload fails after you add the converter, which surprises teams migrating from Newtonsoft.

csharp
public enum Status { Pending, Active, Closed } var options = new JsonSerializerOptions { Converters = { new JsonStringEnumConverter(allowIntegerValues: true) }, }; var envelope = JsonSerializer.Deserialize<Envelope>("""{ "status": "Active" }""", options);

Serializing writes "Active" rather than 1, which keeps payloads readable in logs and stable when enum members are reordered.

Records, init, and constructors

Records with positional parameters deserialize through the primary constructor, and required members must be present unless nullable. A class with a single parameterised constructor needs [JsonConstructor], otherwise the failure is reported for the whole type rather than one property.

csharp
public sealed class Order { [JsonConstructor] public Order(string id, DateTime createdAt, int quantity) { Id = id; CreatedAt = createdAt; Quantity = quantity; } public string Id { get; } public DateTime CreatedAt { get; } public int Quantity { get; } }

Source generation quietly ignores options

With JsonSerializerContext, converters must be declared on the context or on the type; passing a JsonSerializerOptions instance to a source-generated serializer throws at runtime unless the context owns those options.

csharp
[JsonSourceGenerationOptions( PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, NumberHandling = JsonNumberHandling.AllowReadingFromString)] [JsonSerializable(typeof(Order))] public partial class ApiJsonContext : JsonSerializerContext;
csharp
var order = JsonSerializer.Deserialize(json, ApiJsonContext.Default.Order);

This is the version of the fix that works under trimming and ahead-of-time compilation, where reflection-based converters are not available.

Common Compilation/Runtime Mistakes & Version Gotchas

Catching JsonException and returning an empty object. That hides malformed payloads and produces data loss instead of an error. Log the Path and BytePositionInLine from the exception, then return a 400.

Assuming Newtonsoft behaviour carries over. Case-insensitive matching, number coercion and enum names all changed defaults, so a migration that only swaps the namespace produces a wave of these exceptions.

Registering converters on JsonSerializerOptions.Default. The default instance is read-only in recent versions; mutating it throws InvalidOperationException. Keep one shared JsonSerializerOptions instance for the app.

Using PropertyNameCaseInsensitive to fix a wrong contract. If the producer sends order_id and the consumer expects OrderId, relaxing case does not help; the names differ, and a [JsonPropertyName("order_id")] attribute is the accurate fix.

Version floor. JsonNumberHandling arrived in .NET 5; required members in C# 11; JsonSourceGenerationOptions in .NET 7; JsonSerializerOptions.Web in .NET 9. A library targeting netstandard2.0 may resolve an older System.Text.Json than the app expects.

The exception is precise, so the fastest route is to read the Path, compare the payload to the property's declared type, and choose the narrowest fix: an attribute for one field, a converter for one type, an option for a whole API contract. When the payload is the thing in doubt, the JSON formatter shows the exact tokens, and the timestamp converter checks whether a date is ISO 8601 before you write a converter for it.

Official references: How to write custom converters and Immutable types and constructors.

Official references

primary documentation

The C# documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.