Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / C#

Convertitori JSON personalizzati: confini dei valori, errori e formattazione invariante

Implementa un convertitore che legge e scrive esattamente un valore JSON, rifiuta gli input incompatibili e separa la formattazione invariante dalla codifica JSON.

Versione: C# 12 and .NET 8; later runtimes may add compatible features

Sintassi

// 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 e .NET 8, JsonConverter<T> di System.Text.Json.Serialization definisce la lettura e la scrittura di un singolo valore di tipo T. Utf8JsonReader, Utf8JsonWriter, JsonTokenType e JsonException appartengono a System.Text.Json. Il lettore scorre i token JSON UTF-8 solo in avanti; TokenType ne indica il tipo con un valore dell’enumerazione JsonTokenType. Un Number non è uno String contenente cifre.

All’ingresso di Read, il lettore è sul primo token del valore. Per uno scalare, restituisci il risultato senza chiamare reader.Read(); per un oggetto o un array, fermati al EndObject o EndArray corrispondente. Fermarsi prima o andare oltre viola il contratto. Il lettore è un ref struct mutabile: passalo per ref quando il chiamante deve vederne l’avanzamento. In C# 12 non dichiararlo come variabile locale in un metodo async e non usare viste sui byte dei token dopo aver restituito il buffer a un pool.

Verifica Number prima di TryGetInt32(out int value): per altri tipi di token il metodo genera InvalidOperationException; se non riesce a leggere il numero come int restituisce false. || salta l’operando destro quando quello sinistro è vero. Per input incompatibili genera JsonException; il serializzatore può valorizzare Path, LineNumber e BytePositionInLine. Per impostazione predefinita, in lettura un convertitore per un tipo valore non nullable riceve Null; per tipi riferimento e Nullable<T>, il serializzatore di norma gestisce null da sé, salvo che il convertitore imposti HandleNull a true.

Write emette esattamente un valore con il writer fornito, senza rilasciarlo. WriteNumberValue(int) scrive un numero senza virgolette. WriteStringValue(string?) scrive una stringa non nulla tra virgolette e applica le regole di escape di JSON; se l’argomento è null, scrive il letterale JSON null senza virgolette. Non comporre JSON per interpolazione e non disattivare la convalida per lasciar passare input non attendibile.

System.FormattableString.Invariant(FormattableString) restituisce uno string con gli argomenti formattati secondo la cultura invariante. Passa direttamente l’interpolazione o conservala come FormattableString; uno string già formattato non si può riformattare così. F1 produce una cifra decimale, qui 12.5. È formattazione di testo, non serializzazione o escape JSON.

Esempi

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);
}

Risultato

[125,-35]
temperature=12,5
temperature=12.5
rejected: "125"
rejected: 2147483648
rejected: null

`Tenths` memorizza la temperatura in decimi di grado. Due elementi mettono alla prova il confine di lettura; cifre tra virgolette, overflow e `null` vengono rifiutati. Il formato esplicito con virgola dà `temperature=12,5`, quello invariante `temperature=12.5`. Il JSON resta `[125,-35]`.

Lezioni correlate

  • C# · Lezione 58 · Avanzato · Versione: 3

Fonti