CKTIS / C#
System.Text.Json.Serialization.JsonConverter: référence pratique
System.Text.Json.Serialization.JsonConverter: référence pratique: JsonConverter<T> définit une lecture et une écriture personnalisées pour un type précis.
Version : .NET API; verified against .NET 10 reference surface
Syntaxe
System.Text.Json.Serialization.JsonConverter /* select a documented member or constructor */JsonConverter définit une lecture et une écriture personnalisées pour un type précis.
À utiliser lorsque le contrat JSON ne correspond pas au mappage par défaut du serializer.
Read doit consommer exactement le bon token et Write produire une structure JSON valide.
Un appel récursif au serializer avec le même converter peut boucler indéfiniment.
Le programme complet utilise réellement System.Text.Json.Serialization.JsonConverter ; sa sortie stdout exacte attendue est 6.
Exemples
using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;
JsonConverter<int> converter = new DoubleIntConverter();
var options = new JsonSerializerOptions(); options.Converters.Add(converter);
Console.WriteLine(JsonSerializer.Deserialize<int>("3", options));
sealed class DoubleIntConverter : JsonConverter<int> { public override int Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options) => reader.GetInt32() * 2; public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options) => writer.WriteNumberValue(value / 2); }
Résultat
6
Le programme complet utilise réellement `System.Text.Json.Serialization.JsonConverter` ; sa sortie stdout exacte attendue est `6`.