CKTIS / C#
Two-way JSON converters: reading, writing, and validating tokens
Build a System.Text.Json converter that reads and writes one JSON object, rejects invalid tokens, and explicitly applies camel-case naming and null omission.
Version: C# 12 and .NET 8; later runtimes may add compatible features
Syntax
using System.Text.Json;
using System.Text.Json.Serialization;
// Members of JsonConverter<T>:
public abstract T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options);
public abstract void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options);
// Inspect reader.TokenType (a JsonTokenType) before reading a value.
// Reject incompatible input with new JsonException("Expected a JSON string.").In C# 12 and .NET 8, a JsonConverter<T> from System.Text.Json.Serialization defines both directions of conversion. Register it in options.Converters. Utf8JsonReader reads JSON tokens, and Utf8JsonWriter writes JSON values. JsonTokenType identifies the kind of token being read, and JsonException signals invalid JSON or input that does not match the converter's contract. All four are in System.Text.Json. The reader moves forward through UTF-8 input. It is a mutable ref struct: pass it by ref so you advance the caller's cursor rather than a copy, and do not store it in a class field.
The converter's Read starts on the first token of the value. For an object, check StartObject, read the properties, and return on the matching EndObject, not after it. Apply the same rule to arrays; for a scalar, stay on its token. reader.TokenType returns a JsonTokenType enum member; check it before calling a value getter. Number does not guarantee that the value fits in an int, so use TryGetInt32. Throw JsonException for incompatible input; the serializer can supply Path, LineNumber, and BytePositionInLine. Reading too little or too far can also produce a JsonException.
Write emits exactly one complete value through the supplied Utf8JsonWriter; do not dispose or flush it. The serializer applies PropertyNamingPolicy = JsonNamingPolicy.CamelCase and DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull to properties it manages, not to manual writer calls. The example computes the same names in both directions and omits entire null-valued properties only under WhenWritingNull; 0 is still written. It matches names case-sensitively, rejects unknown and duplicate names, and implements the Never and WhenWritingNull omission behaviors, not every serializer setting.
string? is an annotation for compiler null analysis, not a new runtime type or JSON validation. int? is the distinct value type Nullable<int>, representing an integer or no value. By default, the serializer handles nulls for reference types and Nullable<T> without calling their converter; override HandleNull to return true if the converter itself must handle them. This is separate from property omission: WhenWritingNull is write-side only, and whether missing properties or explicit JSON null are accepted on read depends on the contract. Here both forms are accepted for Note and Rank, but not for DisplayName.
Examples
#nullable enable
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
options.Converters.Add(new ProfileCardConverter());
var card = new ProfileCard("Ada", null, null);
Console.WriteLine(JsonSerializer.Serialize(card, options));
var keepNulls = new JsonSerializerOptions(options)
{
DefaultIgnoreCondition = JsonIgnoreCondition.Never
};
Console.WriteLine(JsonSerializer.Serialize(card, keepNulls));
var read = JsonSerializer.Deserialize<ProfileCard>(
"""{"displayName":"Ada","note":null,"rank":0}""", options)
?? throw new JsonException("Expected a non-null profile card.");
Console.WriteLine(JsonSerializer.Serialize(read, options));
try
{
_ = JsonSerializer.Deserialize<ProfileCard>("""{"displayName":42}""", options);
}
catch (JsonException)
{
Console.WriteLine("Rejected: JsonException");
}
sealed record ProfileCard(string DisplayName, string? Note, int? Rank);
sealed class ProfileCardConverter : JsonConverter<ProfileCard>
{
private static string Name(JsonSerializerOptions options, string clrName) =>
options.PropertyNamingPolicy?.ConvertName(clrName) ?? clrName;
public override ProfileCard Read(ref Utf8JsonReader reader, Type typeToConvert,
JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.StartObject)
throw new JsonException("Expected an object.");
string displayNameKey = Name(options, nameof(ProfileCard.DisplayName));
string noteKey = Name(options, nameof(ProfileCard.Note));
string rankKey = Name(options, nameof(ProfileCard.Rank));
var seen = new HashSet<string>(StringComparer.Ordinal);
string? displayName = null;
string? note = null;
int? rank = null;
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.EndObject)
return new ProfileCard(
displayName ?? throw new JsonException("Missing display name."), note, rank);
if (reader.TokenType != JsonTokenType.PropertyName)
throw new JsonException("Expected a property name.");
string key = reader.GetString() ?? throw new JsonException("Missing property name.");
if (!seen.Add(key))
throw new JsonException("Duplicate property.");
if (!reader.Read())
throw new JsonException("Missing property value.");
if (key == displayNameKey && reader.TokenType == JsonTokenType.String)
displayName = reader.GetString();
else if (key == noteKey && reader.TokenType is JsonTokenType.String or JsonTokenType.Null)
note = reader.GetString();
else if (key == rankKey && reader.TokenType == JsonTokenType.Null)
rank = null;
else if (key == rankKey && reader.TokenType == JsonTokenType.Number &&
reader.TryGetInt32(out int number))
rank = number;
else
throw new JsonException("Unknown property or invalid value.");
}
throw new JsonException("Expected the end of the object.");
}
public override void Write(Utf8JsonWriter writer, ProfileCard value, JsonSerializerOptions options)
{
bool omitNulls = options.DefaultIgnoreCondition == JsonIgnoreCondition.WhenWritingNull;
writer.WriteStartObject();
writer.WriteString(Name(options, nameof(ProfileCard.DisplayName)), value.DisplayName);
if (value.Note is not null || !omitNulls)
writer.WriteString(Name(options, nameof(ProfileCard.Note)), value.Note);
if (value.Rank is int rank)
writer.WriteNumber(Name(options, nameof(ProfileCard.Rank)), rank);
else if (!omitNulls)
writer.WriteNull(Name(options, nameof(ProfileCard.Rank)));
writer.WriteEndObject();
}
}Result
{"displayName":"Ada"}
{"displayName":"Ada","note":null,"rank":null}
{"displayName":"Ada","rank":0}
Rejected: JsonExceptionThe first line omits both null-valued properties, the second writes both as null, and the third keeps rank equal to 0 after reading. A number instead of text in displayName produces a JsonException.
Related lessons
- C# · Lesson 39 · Advanced · Version: 3
Sources
- How to write custom converters for JSON serialization
- How to use Utf8JsonReader in System.Text.Json
- Utf8JsonWriter Class
- JsonTokenType Enum
- JsonException Class
- How to customize property names and values with System.Text.Json
- How to ignore properties with System.Text.Json
- Nullable reference types
- Nullable value types