mirror of
https://github.com/SabreTools/SabreTools.Serialization.git
synced 2026-04-05 22:01:33 +00:00
This change looks dramatic, but it's just separating out the already-split namespaces into separate top-level folders. In theory, every single one could be built into their own Nuget package. `SabreTools.Serialization` still builds the normal Nuget package that is used by all other projects and includes all namespaces.
49 lines
1.8 KiB
C#
49 lines
1.8 KiB
C#
#if NETCOREAPP
|
|
|
|
using System;
|
|
using System.Reflection;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
|
|
namespace SabreTools.Wrappers
|
|
{
|
|
/// <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;
|
|
|
|
private class ConcreteInterfaceSerializerOfType<TInterface> : JsonConverter<TInterface>
|
|
{
|
|
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
|
|
public override TInterface Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
|
=> throw new NotImplementedException();
|
|
#else
|
|
public override TInterface? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
|
=> throw new NotImplementedException();
|
|
#endif
|
|
|
|
public override void Write(Utf8JsonWriter writer, TInterface value, JsonSerializerOptions options)
|
|
=> JsonSerializer.Serialize<object>(writer, value!, options);
|
|
}
|
|
|
|
public override JsonConverter CreateConverter(Type type, JsonSerializerOptions options)
|
|
=> (JsonConverter)Activator.CreateInstance(
|
|
typeof(ConcreteInterfaceSerializerOfType<>).MakeGenericType([type]),
|
|
BindingFlags.Instance | BindingFlags.Public,
|
|
binder: null,
|
|
args: [],
|
|
culture: null).ThrowOnNull();
|
|
}
|
|
}
|
|
|
|
#endif
|