Skip to content

Instantly share code, notes, and snippets.

@Pzixel
Created April 9, 2020 13:51
Show Gist options
  • Save Pzixel/a78ea4215b1dad5b06085066ca570081 to your computer and use it in GitHub Desktop.
Save Pzixel/a78ea4215b1dad5b06085066ca570081 to your computer and use it in GitHub Desktop.
using System;
using System.Linq;
using Newtonsoft.Json;
namespace XXX
{
[JsonConverter(typeof(StructWrapperConverter))]
public sealed class StructWrapper<T> where T : struct
{
public T Value { get; }
public StructWrapper(T value)
{
Value = value;
}
}
public class StructWrapperConverter : JsonConverter
{
public override bool CanConvert(Type objectType) =>
objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(StructWrapper<>);
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
Type type = value!.GetType();
var prop = type.GetProperties().Single();
var propVal = prop.GetValue(value, null);
serializer.Serialize(writer, propVal);
}
public override object ReadJson(JsonReader reader, Type objectType, object? existingValue,
JsonSerializer serializer)
{
var argType = objectType.GetGenericArguments().Single();
return serializer.Deserialize(reader, argType)!;
}
public override bool CanRead => true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment