Files
SabreTools.Serialization/SabreTools.Wrappers/ConcreteInterfaceSerializer.cs

49 lines
1.8 KiB
C#
Raw Normal View History

#if NETCOREAPP
2024-11-27 23:43:50 -05:00
using System;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
2026-03-18 16:37:59 -04:00
namespace SabreTools.Wrappers
2024-11-27 23:43:50 -05:00
{
/// <summary>
/// Serializer class for interfaces
/// </summary>
/// <see href="https://stackoverflow.com/a/72775719"/>
internal class ConcreteInterfaceSerializer : JsonConverterFactory
{
public override bool CanConvert(Type typeToConvert) => typeToConvert.IsInterface;
2026-01-27 12:03:01 -05:00
private class ConcreteInterfaceSerializerOfType<TInterface> : JsonConverter<TInterface>
2024-11-27 23:43:50 -05:00
{
static ConcreteInterfaceSerializerOfType()
{
if (!typeof(TInterface).IsAbstract && !typeof(TInterface).IsInterface)
throw new NotImplementedException(string.Format("Concrete class {0} is not supported", typeof(TInterface)));
}
#if NETCOREAPP3_1
2026-01-27 12:03:01 -05:00
public override TInterface Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
=> throw new NotImplementedException();
2024-11-27 23:43:50 -05:00
#else
2026-01-27 12:03:01 -05:00
public override TInterface? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
=> throw new NotImplementedException();
2024-11-27 23:43:50 -05:00
#endif
2026-01-27 12:03:01 -05:00
public override void Write(Utf8JsonWriter writer, TInterface value, JsonSerializerOptions options)
=> JsonSerializer.Serialize<object>(writer, value!, options);
2024-11-27 23:43:50 -05:00
}
2026-01-27 12:03:01 -05:00
public override JsonConverter CreateConverter(Type type, JsonSerializerOptions options)
=> (JsonConverter)Activator.CreateInstance(
2025-11-14 09:06:59 -05:00
typeof(ConcreteInterfaceSerializerOfType<>).MakeGenericType([type]),
2024-11-27 23:43:50 -05:00
BindingFlags.Instance | BindingFlags.Public,
binder: null,
2025-11-14 09:06:59 -05:00
args: [],
2024-11-27 23:43:50 -05:00
culture: null).ThrowOnNull();
}
}
#endif