CKTIS / C#
Conversores JSON personalizados: limites de leitura, erros e formatação invariante
Implemente um conversor que lê e escreve exatamente um valor JSON, rejeita entradas incompatíveis e separa a formatação invariante da codificação JSON.
Versão: C# 12 and .NET 8; later runtimes may add compatible features
Sintaxe
// 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}")Em C# 12 e .NET 8, JsonConverter<T>, de System.Text.Json.Serialization, define como ler e escrever um único valor do tipo T. Utf8JsonReader, Utf8JsonWriter, JsonTokenType e JsonException pertencem a System.Text.Json. O leitor percorre os tokens JSON em UTF-8 apenas para a frente; TokenType indica a categoria através de um valor da enumeração JsonTokenType. Um Number não é um String que contém algarismos.
À entrada de Read, o leitor está no primeiro token do valor. Para um escalar, devolva o resultado sem chamar reader.Read(); para um objeto ou um array, pare no EndObject ou EndArray correspondente. Parar cedo ou avançar demais viola o contrato. O leitor é um ref struct mutável: passe-o por ref se o chamador tiver de ver o seu avanço. Em C# 12, não o declare como variável local num método async nem use vistas dos bytes dos tokens depois de devolver o respetivo buffer a um conjunto de reutilização.
Verifique Number antes de TryGetInt32(out int value): para outros tipos de token, o método lança InvalidOperationException; se não conseguir ler o número como int, devolve false. || não avalia o operando direito quando o esquerdo é verdadeiro. Lance JsonException para entradas incompatíveis; o serializador pode preencher Path, LineNumber e BytePositionInLine. Por predefinição, na leitura, o conversor de um tipo valor que não admite null recebe Null; para tipos referência e Nullable<T>, o serializador trata normalmente null, exceto se o conversor definir HandleNull como true.
Write emite exatamente um valor com o escritor fornecido, sem o libertar. WriteNumberValue(int) emite um número sem aspas. WriteStringValue(string?) escreve uma cadeia de caracteres não nula entre aspas e aplica as regras de escape do JSON; se o argumento for null, escreve o literal JSON null sem aspas. Não componha JSON por interpolação nem desative a validação para deixar passar entradas não fidedignas.
System.FormattableString.Invariant(FormattableString) devolve um string com os argumentos formatados segundo a cultura invariante. Passe a interpolação diretamente ou guarde-a como FormattableString; não pode reformatar assim um string já formatado. F1 dá uma casa decimal, aqui 12.5. Isto é formatação de texto, não serialização nem escape de JSON.
Exemplos
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);
}Resultado
[125,-35] temperature=12,5 temperature=12.5 rejected: "125" rejected: 2147483648 rejected: null
`Tenths` guarda a temperatura em décimos de grau. Dois elementos põem à prova o limite de leitura; são rejeitados os algarismos entre aspas, o valor fora do intervalo e `null`. O formato explícito com vírgula dá `temperature=12,5`, e o invariante dá `temperature=12.5`. O JSON mantém-se `[125,-35]`.
Lições relacionadas
- C# · Lição 58 · Avançado · Versão: 3
Fontes
- 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)