-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathSingleValueObjectConverter.cs
More file actions
55 lines (45 loc) · 1.93 KB
/
SingleValueObjectConverter.cs
File metadata and controls
55 lines (45 loc) · 1.93 KB
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
55
// Copyright (c) TotalSoft.
// This source code is licensed under the MIT license.
using System;
using System.Collections.Concurrent;
using System.Reflection;
using Newtonsoft.Json;
namespace NBB.Domain
{
public class SingleValueObjectConverter : JsonConverter
{
private static readonly ConcurrentDictionary<Type, Type> ConstructorArgumentTypes = new();
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var identityValue = value?.GetType().GetProperty("Value")?.GetValue(value, null);
serializer.Serialize(writer, identityValue);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var parameterType = ConstructorArgumentTypes[objectType];
var value = serializer.Deserialize(reader, parameterType);
var ci = objectType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null, new[] {parameterType}, null);
if (ci == null)
{
throw new Exception($"No suitable constructor found for {objectType.Name} with parameter of type {parameterType.Name}");
}
return ci.Invoke(new[] {value});
}
public override bool CanConvert(Type objectType)
{
var currentType = objectType;
while (currentType != null)
{
if (currentType.IsGenericType &&
currentType.GetGenericTypeDefinition() == typeof(SingleValueObject<>))
{
ConstructorArgumentTypes[objectType] = currentType.GenericTypeArguments[0];
return true;
}
currentType = currentType.BaseType;
}
return false;
}
}
}