Created
April 9, 2020 13:51
-
-
Save Pzixel/a78ea4215b1dad5b06085066ca570081 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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