using System.Text.Json.Serialization;
namespace TestJsonConverterBug
static readonly JsonSerializerOptions _options = new();
Console.WriteLine("Environment version: {0} ({1}), {2}", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , Environment.Version, Environment.OSVersion);
Console.WriteLine("System.Text.Json version: " + typeof(JsonSerializer).Assembly.FullName);
_options.Converters.Add(new JsonEncodingConverter());
TestAttributeSerialize();
TestAttributeDeserialize();
static void TestOptions()
var obj = new SerializableClass1();
var json = JsonSerializer.Serialize(obj, _options);
var enc = JsonSerializer.Deserialize<SerializableClass1>(json, _options);
Console.WriteLine("TestOptions(): {0} round-tripped successfully with JSON {1}.\n", enc, json);
Assert.That(obj.Encoding == enc?.Encoding);
static void TestAttributeSerialize()
var obj = new SerializableClass2();
var json = JsonSerializer.Serialize(obj);
Console.WriteLine("TestAttributeSerialize(): {0} serialized successfully with JSON {1}.\n", obj, json);
static void TestAttributeDeserialize()
var obj = new SerializableClass2();
var json = JsonSerializer.Serialize(obj, _options);
var enc = JsonSerializer.Deserialize<SerializableClass2>(json);
Console.WriteLine("TestOptions(): {0} round-tripped successfully with JSON {1}.\n", enc, json);
Assert.That(obj.Encoding == enc?.Encoding);
internal class SerializableClass1
public SerializableClass1()
Encoding = Encoding.ASCII;
public Encoding Encoding { get; set; }
internal class SerializableClass2
public SerializableClass2()
Encoding = Encoding.ASCII;
[JsonInclude, JsonPropertyName("Encoding")]
string EncodingName { get => Encoding?.EncodingName!; set => Encoding = Encoding.GetEncoding(value); }
public Encoding Encoding { get; set; }
internal class JsonEncodingConverter : JsonConverter<Encoding>
public override bool CanConvert(Type typeToConvert)
=> typeToConvert.IsAssignableTo(typeof(Encoding));
public override Encoding? Read(
ref Utf8JsonReader reader,
JsonSerializerOptions options
) => Encoding.GetEncoding(reader.GetString()!);
public override void Write(
JsonSerializerOptions options
) => writer.WriteStringValue(value.EncodingName);