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