Base de conocimientosCentro de exámenes
ESEspañol
Elegir idioma13

CKTIS / C#

Convertidores JSON personalizados: límites de lectura, errores y formato invariable

Implementa un convertidor que lee y escribe exactamente un valor JSON, rechaza entradas incompatibles y distingue el formato invariable de la codificación JSON.

Versión: C# 12 and .NET 8; later runtimes may add compatible features

Sintaxis

// 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}")

En C# 12 y .NET 8, JsonConverter<T>, de System.Text.Json.Serialization, define cómo leer y escribir un único valor de tipo T. Utf8JsonReader, Utf8JsonWriter, JsonTokenType y JsonException pertenecen a System.Text.Json. El lector recorre los tokens JSON en UTF-8 solo hacia delante; TokenType indica su clase con un valor de la enumeración JsonTokenType. Number no equivale a un String con dígitos.

Al entrar en Read, el lector está en el primer token del valor. Para un escalar, devuelve el resultado sin llamar a reader.Read(); para un objeto o una matriz, detente en el EndObject o EndArray correspondiente. Detenerse antes o avanzar de más incumple el contrato. El lector es un ref struct mutable: pásalo por ref si el llamador debe ver su avance. En C# 12, no lo declares como variable local en un método async ni uses vistas de los bytes de un token después de devolver su búfer al grupo de reutilización.

Comprueba Number antes de TryGetInt32(out int value): con otros tipos de token lanza InvalidOperationException; si no puede leer el número como int, devuelve false. || omite el operando derecho cuando el izquierdo es verdadero. Lanza JsonException para entradas incompatibles; el serializador puede proporcionar Path, LineNumber y BytePositionInLine. Por defecto, al leer, un convertidor de un tipo de valor no anulable recibe Null; para los tipos de referencia y Nullable<T>, el serializador suele gestionar null directamente, salvo que el convertidor establezca HandleNull en true.

Write emite exactamente un valor con el escritor recibido, sin liberarlo. WriteNumberValue(int) emite un número sin comillas. WriteStringValue(string?) escribe una cadena no nula entre comillas y aplica las reglas de escape de JSON; si el argumento es null, escribe el literal JSON null sin comillas. No construyas JSON por interpolación ni desactives la validación para dejar pasar entradas no confiables.

System.FormattableString.Invariant(FormattableString) devuelve un string con los argumentos formateados según la referencia cultural invariable. Pasa la interpolación directamente o consérvala como FormattableString; un string ya formateado no se puede volver a formatear así. F1 da una cifra decimal, aquí 12.5. Esto es formato de texto, no serialización ni escape de JSON.

Ejemplos

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 la temperatura en décimas de grado. Dos elementos ponen a prueba el límite de lectura; se rechazan los dígitos entre comillas, el desbordamiento y `null`. El formato explícito con coma produce `temperature=12,5`; el invariable, `temperature=12.5`. El JSON sigue siendo `[125,-35]`.

Lecciones relacionadas

  • C# · Lección 58 · Avanzado · Versión: 3

Fuentes