|
| 1 | +// ******************************************************************** |
| 2 | +// |
| 3 | +// Copyright (c) RimuruDev |
| 4 | +// Contact information: |
| 5 | +// Email: rimuru.dev@gmail.com |
| 6 | +// GitHub: https://github.com/RimuruDev |
| 7 | +// LinkedIn: https://www.linkedin.com/in/rimuru/ |
| 8 | +// |
| 9 | +// ******************************************************************** |
| 10 | + |
| 11 | +using System; |
| 12 | +using RimuruDev; |
| 13 | +using UnityEngine; |
| 14 | +using Newtonsoft.Json; |
| 15 | + |
| 16 | +namespace AbyssMoth.Internal.Codebase.Runtime.HalloweenEventLogic.Storage |
| 17 | +{ |
| 18 | + [HelpURL("https://github.com/RimuruDev/Unity-ReactivePropertyConverter.git")] |
| 19 | + public sealed class ReactivePropertyConverter : JsonConverter |
| 20 | + { |
| 21 | + private const string ReactivePropertyName = "Value"; |
| 22 | + private const int FirstGenericArgument = 0; |
| 23 | + |
| 24 | + public override bool CanConvert(Type objectType) => |
| 25 | + objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(ReactiveProperty<>); |
| 26 | + |
| 27 | + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) |
| 28 | + { |
| 29 | + if (value != null) |
| 30 | + { |
| 31 | + var valueProperty = value.GetType().GetProperty(ReactivePropertyName); |
| 32 | + |
| 33 | + if (valueProperty != null) |
| 34 | + { |
| 35 | + var underlyingValue = valueProperty.GetValue(value); |
| 36 | + |
| 37 | + serializer.Serialize(writer, underlyingValue); |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) |
| 43 | + { |
| 44 | + var valueType = objectType.GetGenericArguments()[FirstGenericArgument]; |
| 45 | + |
| 46 | + var value = serializer.Deserialize(reader, valueType); |
| 47 | + |
| 48 | + var reactivePropertyType = typeof(ReactiveProperty<>).MakeGenericType(valueType); |
| 49 | + var reactiveProperty = Activator.CreateInstance(reactivePropertyType, value); |
| 50 | + |
| 51 | + return reactiveProperty; |
| 52 | + } |
| 53 | + } |
| 54 | +} |
0 commit comments