mirror of
https://github.com/PluralKit/PluralKit.git
synced 2026-02-04 04:56:49 +00:00
Port more things!
This commit is contained in:
parent
f6fb8204bb
commit
47b16dc51b
26 changed files with 332 additions and 186 deletions
43
Myriad/Serialization/OptionalConverter.cs
Normal file
43
Myriad/Serialization/OptionalConverter.cs
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
using System;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
using Myriad.Utils;
|
||||
|
||||
namespace Myriad.Serialization
|
||||
{
|
||||
public class OptionalConverter: JsonConverter<IOptional>
|
||||
{
|
||||
public override IOptional? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
var innerType = typeToConvert.GetGenericArguments()[0];
|
||||
var inner = JsonSerializer.Deserialize(ref reader, innerType, options);
|
||||
|
||||
// TODO: rewrite to JsonConverterFactory to cut down on reflection
|
||||
return (IOptional?) Activator.CreateInstance(
|
||||
typeof(Optional<>).MakeGenericType(innerType),
|
||||
BindingFlags.Instance | BindingFlags.Public,
|
||||
null,
|
||||
new[] {inner},
|
||||
null);
|
||||
}
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, IOptional value, JsonSerializerOptions options)
|
||||
{
|
||||
var innerType = value.GetType().GetGenericArguments()[0];
|
||||
JsonSerializer.Serialize(writer, value.GetValue(), innerType, options);
|
||||
}
|
||||
|
||||
public override bool CanConvert(Type typeToConvert)
|
||||
{
|
||||
if (!typeToConvert.IsGenericType)
|
||||
return false;
|
||||
|
||||
if (typeToConvert.GetGenericTypeDefinition() != typeof(Optional<>))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue