CSharp · Console
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
public class Program
{
public static void Main()
{
var obj = new MyClass
{
Break = new List<MyRange<DateTimeOffset>>
{
new MyRange<DateTimeOffset>(DateTimeOffset.MinValue, DateTimeOffset.MaxValue)
}
};
try
{
JsonSerializer.Serialize(obj);
Console.WriteLine("Write converter not called.");
}
catch (NotImplementedException)
{
Console.WriteLine("Write converter called.");
}
try
{
JsonSerializer.Deserialize<MyClass>(@"{""Break"":[]}");
Console.WriteLine("Read converter not called.");
}
catch (NotImplementedException)
{
Console.WriteLine("Read converter called.");
}
}
public class MyClass
{
[JsonConverter(typeof(CustomBreakConverter))]
public IEnumerable<MyRange<DateTimeOffset>> Break { get; set; }
}
public class CustomBreakConverter : JsonConverter<IEnumerable<MyRange<DateTimeOffset>>>
{
public override IEnumerable<MyRange<DateTimeOffset>> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
throw new NotImplementedException();
public override void Write(Utf8JsonWriter writer, IEnumerable<MyRange<DateTimeOffset>> value, JsonSerializerOptions options) =>
throw new NotImplementedException();
}
public struct MyRange<T>
{
public T Start { get; }
public T End { get; }
public MyRange(T start, T end) => (Start, End) = (start, end);
}
}