PluralKit/Myriad/Serialization/OptionalConverter.cs

47 lines
1.4 KiB
C#
Raw Normal View History

2020-12-24 13:52:44 +00:00
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
using Myriad.Utils;
namespace Myriad.Serialization;
public class OptionalConverterFactory: JsonConverterFactory
2020-12-24 13:52:44 +00:00
{
public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options)
2020-12-24 13:52:44 +00:00
{
var innerType = typeToConvert.GetGenericArguments()[0];
return (JsonConverter?)Activator.CreateInstance(
typeof(Inner<>).MakeGenericType(innerType),
BindingFlags.Instance | BindingFlags.Public,
null,
null,
null);
}
public override bool CanConvert(Type typeToConvert)
{
if (!typeToConvert.IsGenericType)
return false;
2021-08-27 15:03:47 +00:00
if (typeToConvert.GetGenericTypeDefinition() != typeof(Optional<>))
return false;
return true;
}
public class Inner<T>: JsonConverter<Optional<T>>
{
public override Optional<T> Read(ref Utf8JsonReader reader, Type typeToConvert,
JsonSerializerOptions options)
2020-12-25 12:58:45 +00:00
{
var inner = JsonSerializer.Deserialize<T>(ref reader, options);
return new Optional<T>(inner!);
2020-12-24 13:52:44 +00:00
}
public override void Write(Utf8JsonWriter writer, Optional<T> value, JsonSerializerOptions options)
2020-12-24 13:52:44 +00:00
{
JsonSerializer.Serialize(writer, value.HasValue ? value.GetValue() : default, typeof(T), options);
2020-12-24 13:52:44 +00:00
}
}
}