CKTIS / C#
Convertidores JSON bidireccionales: lectura, escritura y validación de tokens
Crea un convertidor de System.Text.Json que lea y escriba un objeto JSON, rechace tokens no válidos y aplique explícitamente camelCase y la omisión de valores null.
Versión: C# 12 and .NET 8; later runtimes may add compatible features
Sintaxis
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.").En C# 12 y .NET 8, JsonConverter<T> de System.Text.Json.Serialization define los dos sentidos de la conversión. Regístralo en options.Converters. Utf8JsonReader, Utf8JsonWriter, JsonTokenType y JsonException pertenecen a System.Text.Json. El lector solo avanza por la entrada UTF-8. Es un ref struct mutable: pásalo mediante ref para avanzar el cursor original en lugar de una copia y no lo guardes en un campo de clase.
El Read del convertidor empieza en el primer token del valor. Si es un objeto, comprueba StartObject, lee las propiedades y regresa con el cursor en el EndObject correspondiente, no después. Aplica la misma regla a los arrays; con un escalar, quédate en su token. reader.TokenType devuelve un miembro de la enumeración JsonTokenType; compruébalo antes de extraer el valor. Number no garantiza que el número quepa en un int, así que usa TryGetInt32. Lanza JsonException ante entradas incompatibles; el serializador puede completar Path, LineNumber y BytePositionInLine. Leer de menos o de más también puede provocar una JsonException.
Write escribe exactamente un valor completo con el Utf8JsonWriter suministrado, sin llamar a Dispose ni a Flush. El serializador aplica PropertyNamingPolicy = JsonNamingPolicy.CamelCase y DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull a las propiedades que gestiona, no a las llamadas manuales al writer. El ejemplo calcula los mismos nombres en ambos sentidos y omite por completo las propiedades con valor null solo con WhenWritingNull; 0 sí se escribe. Distingue mayúsculas y minúsculas, rechaza nombres desconocidos y duplicados e implementa las reglas de omisión Never y WhenWritingNull, no toda la configuración del serializador.
string? es una anotación para el análisis de nulabilidad del compilador, no un nuevo tipo en tiempo de ejecución ni una validación JSON. int? es el tipo de valor distinto Nullable<int>, que representa un entero o la ausencia de valor. De forma predeterminada, el serializador trata los valores nulos de los tipos de referencia y de Nullable<T> sin llamar a su convertidor. Si este debe tratarlos, sobrescribe HandleNull para que devuelva true. Esto es independiente de la omisión de propiedades: WhenWritingNull solo afecta a la escritura y el contrato decide si se aceptan propiedades ausentes o un null explícito en el JSON de entrada. Aquí se aceptan ambas formas para Note y Rank, pero no para DisplayName.
Ejemplos
#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: JsonExceptionLa primera línea omite las dos propiedades con valor null, la segunda escribe ambas como null y la tercera conserva rank con el valor 0 tras la lectura. Un número en vez de texto en displayName provoca una JsonException.
Lecciones relacionadas
- C# · Lección 39 · Avanzado · Versión: 3
Fuentes
- 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