CKTIS / C#
Convertitori JSON bidirezionali: lettura, scrittura e convalida dei token
Crea un convertitore System.Text.Json che legge e scrive un oggetto JSON, rifiuta i token non validi e applica esplicitamente camelCase e l’omissione dei valori null.
Versione: C# 12 and .NET 8; later runtimes may add compatible features
Sintassi
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 e .NET 8, JsonConverter<T> di System.Text.Json.Serialization definisce entrambe le direzioni della conversione. Registralo in options.Converters. Utf8JsonReader, Utf8JsonWriter, JsonTokenType e JsonException appartengono a System.Text.Json. Il lettore avanza senza tornare indietro nei dati UTF-8. È un ref struct mutabile: passalo tramite ref per spostare il cursore originale invece di una copia e non conservarlo in un campo di classe.
Il metodo Read del convertitore parte dal primo token del valore. Per un oggetto, verifica StartObject, leggi le proprietà e termina con il cursore sul corrispondente EndObject, non oltre. Applica la stessa regola agli array; per uno scalare, resta sul suo token. reader.TokenType restituisce un membro dell’enumerazione JsonTokenType: controllalo prima di estrarre il valore. Number non garantisce che il numero sia rappresentabile come int, quindi usa TryGetInt32. Per un input incompatibile, genera una JsonException; il serializzatore può valorizzare Path, LineNumber e BytePositionInLine. Anche leggere troppo poco o andare oltre il valore può provocare una JsonException.
Write scrive esattamente un valore completo con lo Utf8JsonWriter fornito, senza chiamare Dispose o Flush. Il serializzatore applica PropertyNamingPolicy = JsonNamingPolicy.CamelCase e DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull alle proprietà che gestisce, non alle chiamate manuali al writer. L’esempio calcola gli stessi nomi in entrambe le direzioni e omette interamente le proprietà con valore null solo con WhenWritingNull; 0 viene comunque scritto. Distingue maiuscole e minuscole, rifiuta nomi sconosciuti e duplicati e implementa le regole di omissione Never e WhenWritingNull, non tutte le impostazioni del serializzatore.
string? è un’annotazione per l’analisi dei valori null da parte del compilatore, non un nuovo tipo a runtime né una convalida JSON. int? è il tipo valore distinto Nullable<int>, che rappresenta un intero o l’assenza di un valore. Per impostazione predefinita, il serializzatore gestisce i valori null dei tipi riferimento e di Nullable<T> senza chiamare il loro convertitore. Se deve gestirli il convertitore, esegui l’override di HandleNull affinché restituisca true. L’omissione delle proprietà è separata: WhenWritingNull vale solo in scrittura; è il contratto a decidere se in lettura accettare proprietà mancanti o un null esplicito nel JSON. Qui entrambe le forme sono accettate per Note e Rank, ma non per DisplayName.
Esempi
#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();
}
}Risultato
{"displayName":"Ada"}
{"displayName":"Ada","note":null,"rank":null}
{"displayName":"Ada","rank":0}
Rejected: JsonExceptionLa prima riga omette entrambe le proprietà con valore null, la seconda le scrive entrambe come null e la terza conserva rank uguale a 0 dopo la lettura. Un numero anziché del testo in displayName provoca una JsonException.
Lezioni correlate
- C# · Lezione 39 · Avanzato · Versione: 3
Fonti
- 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