-
Notifications
You must be signed in to change notification settings - Fork 73
/
ElementConverter.cs
97 lines (88 loc) · 2.95 KB
/
ElementConverter.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
using Elements.Interfaces;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
namespace Elements.Serialization
{
/// <summary>
/// The serialization converter for elements.
/// </summary>
public class ElementConverter : JsonConverter
{
private List<Type> _elementTypes;
/// <summary>
/// Construct an ElementConverter.
/// </summary>
public ElementConverter()
{
try
{
_elementTypes = Assembly.GetExecutingAssembly().GetTypes().Where(t=>typeof(IElement).IsAssignableFrom(t)).ToList();
}
catch(System.Reflection.ReflectionTypeLoadException ex)
{
foreach(var x in ex.LoaderExceptions)
{
Console.WriteLine(x.Message);
}
}
}
/// <summary>
/// Can this converter converter objects of the provided type?
/// </summary>
/// <param name="objectType"></param>
/// <returns></returns>
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Element);
}
/// <summary>
/// Can this converter read json?
/// </summary>
public override bool CanRead
{
get{return true;}
}
/// <summary>
/// Can this converter write json?
/// </summary>
public override bool CanWrite
{
get{return false;}
}
/// <summary>
/// Read json.
/// </summary>
/// <param name="reader"></param>
/// <param name="objectType"></param>
/// <param name="existingValue"></param>
/// <param name="serializer"></param>
/// <exception cref="System.Exception">Thrown when a type matching the deserialized type name cannot be found.</exception>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var obj = JObject.Load(reader);
var typeName = (string)obj.GetValue("type");
// Find a type with the fullname
var foundType = _elementTypes.FirstOrDefault(t=>t.FullName.ToLower() == typeName);
if(foundType == null)
{
throw new Exception($"The object with type name, {typeName}, could not be deserialzed.");
}
return obj.ToObject(foundType, serializer);
}
/// <summary>
/// Write json.
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
/// <param name="serializer"></param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
}