CKTIS / C#
Custom JSON converters: token boundaries, errors, and invariant formatting
Implement a converter that reads and writes exactly one JSON value, rejects incompatible input, and keeps invariant text formatting separate from JSON encoding.
Version: C# 12 and .NET 8; later runtimes may add compatible features
Syntax
// C# 12 / .NET 8 — override signatures inside a JsonConverter<T> subclass
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
// Typical expressions inside method bodies:
reader.TokenType == JsonTokenType.Number
reader.TryGetInt32(out int value)
throw new JsonException("Expected an Int32 JSON number.");
writer.WriteNumberValue(value);
FormattableString.Invariant($"temperature={value / 10m:F1}")In C# 12 and .NET 8, JsonConverter<T> in System.Text.Json.Serialization defines how to read and write one T. Utf8JsonReader, Utf8JsonWriter, JsonTokenType, and JsonException are in System.Text.Json. The reader moves forward through UTF-8 JSON tokens; TokenType reports the kind as a JsonTokenType enum value. Number is not the same as a String containing digits.
Read receives the reader on the value's first token. For a scalar, return without calling reader.Read(); for an object or array, stop on the matching EndObject or EndArray. Stopping early or advancing too far violates the converter contract. The reader is a mutable ref struct: pass it by ref when the caller must see its progress. In C# 12, don't declare it as a local in an async method or use token byte views after returning their buffer to a pool.
Check for Number before TryGetInt32(out int value): it throws InvalidOperationException on other token kinds and returns false for a number it cannot parse as an int. The || operator skips its right operand when the left is true. Throw JsonException for incompatible input; the serializer can supply Path, LineNumber, and BytePositionInLine. By default, a converter for a non-nullable value type receives Null on read; for reference and Nullable<T> types, the serializer normally handles null itself unless the converter sets HandleNull to true.
Write emits exactly one value with the supplied writer without disposing it. WriteNumberValue(int) emits an unquoted number. WriteStringValue(string?) writes a non-null string in quotes with JSON escaping; a null argument produces the unquoted JSON literal null. Don't assemble JSON by interpolation or disable validation to let untrusted input through.
System.FormattableString.Invariant(FormattableString) returns a string with arguments formatted using invariant culture. Pass the interpolation directly or keep it as a FormattableString; an already formatted string can't be reformatted this way. F1 gives one decimal place, here 12.5. This is text formatting, not JSON serialization or escaping.
Examples
using System;
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
var options = new JsonSerializerOptions();
options.Converters.Add(new TenthsConverter());
Tenths[] values = JsonSerializer.Deserialize<Tenths[]>("[125,-35]", options)!;
Console.WriteLine(JsonSerializer.Serialize(values, options));
FormattableString text = $"temperature={values[0].Value / 10m:F1}";
var commaFormat = new NumberFormatInfo { NumberDecimalSeparator = "," };
Console.WriteLine(text.ToString(commaFormat));
Console.WriteLine(FormattableString.Invariant(text));
foreach (string bad in new[] { "\"125\"", "2147483648", "null" })
{
try
{
_ = JsonSerializer.Deserialize<Tenths>(bad, options);
throw new InvalidOperationException("Expected JsonException.");
}
catch (JsonException)
{
Console.WriteLine($"rejected: {bad}");
}
}
readonly record struct Tenths(int Value);
sealed class TenthsConverter : JsonConverter<Tenths>
{
public override Tenths Read(ref Utf8JsonReader reader, Type typeToConvert,
JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.Number || !reader.TryGetInt32(out int value))
throw new JsonException("Expected an Int32 JSON number.");
return new Tenths(value);
}
public override void Write(Utf8JsonWriter writer, Tenths value,
JsonSerializerOptions options) => writer.WriteNumberValue(value.Value);
}Result
[125,-35] temperature=12,5 temperature=12.5 rejected: "125" rejected: 2147483648 rejected: null
`Tenths` stores temperature in tenths of a degree. Two elements exercise the read boundary; quoted digits, overflow, and `null` are rejected. An explicit comma format gives `temperature=12,5`, while invariant formatting gives `temperature=12.5`. The JSON remains `[125,-35]`.
Related lessons
- C# · Lesson 58 · Advanced · Version: 3
Sources
- How to write custom converters for JSON serialization
- How to use Utf8JsonReader in System.Text.Json
- Utf8JsonWriter Class (System.Text.Json)
- JsonTokenType Enum (System.Text.Json)
- Utf8JsonReader.TryGetInt32(Int32) Method (System.Text.Json)
- JsonException Class (System.Text.Json)
- FormattableString.Invariant(FormattableString) Method (System)
- String interpolation using $
- ref structure types (C# reference)
- How to use Utf8JsonWriter in System.Text.Json
- NumberFormatInfo Class (System.Globalization)