PluralKit/Myriad/Serialization/OptionalConverter.cs

48 lines
1.5 KiB
C#
Raw Normal View History

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