Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / C#

Conversores JSON bidirecionais: leitura, escrita e validação de tokens

Cria um conversor de System.Text.Json que lê e escreve um objeto JSON, rejeita tokens inválidos e aplica explicitamente camelCase e a omissão de valores null.

Versão: C# 12 and .NET 8; later runtimes may add compatible features

Sintaxe

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.").

Em C# 12 e .NET 8, JsonConverter<T> de System.Text.Json.Serialization define os dois sentidos da conversão. Regista-o em options.Converters. Utf8JsonReader, Utf8JsonWriter, JsonTokenType e JsonException pertencem a System.Text.Json. O leitor só avança nos dados UTF-8. É um ref struct mutável: passa-o por ref para avançar o cursor original em vez de uma cópia e não o guardes num campo de classe.

O Read do conversor começa no primeiro token do valor. Para um objeto, verifica StartObject, lê as propriedades e regressa com o cursor no EndObject correspondente, não depois. Aplica a mesma regra aos arrays; para um escalar, fica no respetivo token. reader.TokenType devolve um membro da enumeração JsonTokenType; verifica-o antes de extrair o valor. Number não garante que o número caiba num int, por isso usa TryGetInt32. Lança JsonException se os dados forem incompatíveis; o serializador pode preencher Path, LineNumber e BytePositionInLine. Ler de menos ou de mais também pode provocar uma JsonException.

Write escreve exatamente um valor completo com o Utf8JsonWriter fornecido, sem chamar Dispose nem Flush. O serializador aplica PropertyNamingPolicy = JsonNamingPolicy.CamelCase e DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull às propriedades que gere, não às chamadas manuais ao writer. O exemplo calcula os mesmos nomes nos dois sentidos e omite propriedades inteiras com valor null apenas com WhenWritingNull; 0 continua a ser escrito. Distingue maiúsculas de minúsculas, rejeita nomes desconhecidos ou repetidos e implementa as regras de omissão Never e WhenWritingNull, não todas as definições do serializador.

string? é uma anotação para a análise de valores nulos pelo compilador, não um novo tipo em tempo de execução nem validação de JSON. int? é o tipo de valor distinto Nullable<int>, que representa um inteiro ou a ausência de valor. Por predefinição, o serializador trata valores nulos de tipos de referência e de Nullable<T> sem chamar o respetivo conversor. Se o conversor tiver de os tratar, redefine HandleNull para devolver true. Isto é independente da omissão de propriedades: WhenWritingNull só afeta a escrita, e o contrato determina se a leitura aceita propriedades em falta ou um null explícito no JSON. Aqui, ambas as formas são aceites para Note e Rank, mas não para DisplayName.

Exemplos

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

Resultado

{"displayName":"Ada"}
{"displayName":"Ada","note":null,"rank":null}
{"displayName":"Ada","rank":0}
Rejected: JsonException

A primeira linha omite as duas propriedades com valor null, a segunda escreve ambas como null e a terceira mantém rank igual a 0 após a leitura. Um número em vez de texto em displayName provoca uma JsonException.

Lições relacionadas

  • C# · Lição 39 · Avançado · Versão: 3

Fontes