Znalostní bázeCentrum zkoušek
CSČeština
Vybrat jazyk13

CKTIS / C#

System.Text.Json.Serialization.JsonConverter: praktická reference

System.Text.Json.Serialization.JsonConverter: praktická reference: JsonConverter<T> definuje vlastní čtení a zápis konkrétního typu.

Verze: .NET API; verified against .NET 10 reference surface

Syntaxe

System.Text.Json.Serialization.JsonConverter /* select a documented member or constructor */

JsonConverter definuje vlastní čtení a zápis konkrétního typu.

Použijte, když kontrakt JSON neodpovídá výchozímu mapování serializer.

Read musí spotřebovat přesně správný token a Write vytvořit platnou strukturu JSON.

Rekurzivní volání serializer se stejným converter se může nekonečně zacyklit.

Úplný program skutečně používá System.Text.Json.Serialization.JsonConverter; přesně očekávaný stdout je 6.

Příklady

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

Výsledek

6

Úplný program skutečně používá `System.Text.Json.Serialization.JsonConverter`; přesně očekávaný stdout je `6`.

Zdroje