Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

System.Text.Json.Serialization.JsonConverter: practical reference

System.Text.Json.Serialization.JsonConverter: practical reference: JsonConverter<T> defines custom reading and writing for a specific type.

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

Syntax

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

JsonConverter defines custom reading and writing for a specific type.

Use it when the JSON contract does not match the serializer default mapping.

Read must consume exactly the correct token, and Write must produce valid JSON structure.

Recursively invoking the serializer with the same converter can loop forever.

The complete program actually uses System.Text.Json.Serialization.JsonConverter; its exact expected stdout is 6.

Examples

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

Result

6

The complete program actually uses `System.Text.Json.Serialization.JsonConverter`; its exact expected stdout is `6`.

Sources