Table of Contents

DynamicJsonConverter Class

Definition

Namespace
Cuemon.Extensions.Text.Json
Assemblies
Cuemon.Extensions.Text.Json.dll
Source
src/Cuemon.Extensions.Text.Json/DynamicJsonConverter.cs

Provides a factory based way to create and wrap an JsonConverter implementation.

public static class DynamicJsonConverter
Inheritance
object
DynamicJsonConverter

Examples

The following example shows how to register a custom JSON converter for the Version type using DynamicJsonConverter. It serializes a version to JSON and deserializes it back, printing each result.

using System;
using System.Text.Json;
using Cuemon.Extensions.Text.Json;

namespace Cuemon.Extensions.Text.Json;

public class DynamicJsonConverterExample
{
    public void Demonstrate()
    {
        var options = new JsonSerializerOptions();
        options.Converters.Add(DynamicJsonConverter.Create<Version>(
            writer: (utf8Writer, value, _) => utf8Writer.WriteStringValue(value.ToString()),
            reader: (ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions) => Version.Parse(reader.GetString())
        ));

        var version = new Version("5.0.0");
        string json = JsonSerializer.Serialize(version, options);
        Console.WriteLine(json);

        var deserialized = JsonSerializer.Deserialize<Version>("\"6.0.0\"", options);
        Console.WriteLine(deserialized);
    }
}

Methods

Name Description
Create(Func<Type, bool>, Func<Type, JsonSerializerOptions, JsonConverter>)

Creates a dynamic instance of an JsonConverter implementation wrapping CanConvert(Type) through predicate and CreateConverter(Type, JsonSerializerOptions) through converterFactory.

Create(Type, Func<Type, JsonSerializerOptions, JsonConverter>)

Creates a dynamic instance of an JsonConverter implementation wrapping CanConvert(Type) through typeToConvert and CreateConverter(Type, JsonSerializerOptions) through converterFactory.

Create<T>(Utf8JsonWriterAction<T>, Utf8JsonReaderFunc<T>)

Creates a dynamic instance of an JsonConverter implementation wrapping Write(Utf8JsonWriter, T, JsonSerializerOptions) through writer and Read(ref Utf8JsonReader, Type, JsonSerializerOptions) through reader.

Create<T>(Func<Type, bool>, Utf8JsonWriterAction<T>, Utf8JsonReaderFunc<T>)

Creates a dynamic instance of an JsonConverter implementation wrapping Write(Utf8JsonWriter, T, JsonSerializerOptions) through writer and Read(ref Utf8JsonReader, Type, JsonSerializerOptions) through reader.