Nuke.Unreal
Build Unreal apps in Style.
Loading...
Searching...
No Matches
EnumerationJsonConverter.cs
1using System;
2using System.Collections.Generic;
3using System.ComponentModel;
4using System.Linq;
5using System.Threading.Tasks;
6using Newtonsoft.Json;
7using Nuke.Common;
8using Nuke.Common.Tooling;
9
10namespace Nuke.Unreal;
11
12public class EnumerationJsonConverter<T> : JsonConverter where T : Enumeration
13{
14 public override bool CanConvert(Type objectType)
15 {
16 return objectType.IsClass && objectType.IsAssignableTo(typeof(Enumeration));
17 }
18
19 public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
20 {
21 if (reader.Value is string value)
22 {
23 try
24 {
25 var result = TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(value!);
26 Assert.NotNull(result, $"'{value}' is not a valid {typeof(T).Name}");
27 return result;
28 }
29 catch (Exception e)
30 {
31 throw new AggregateException($"'{value}' is not a valid {typeof(T).Name}", e);
32 }
33 }
34 Assert.True(reader.TokenType == JsonToken.None
35 || reader.TokenType == JsonToken.Null
36 || reader.TokenType == JsonToken.Undefined,
37 $"JSON value was neither a string, nor one of the 'not-existing' types. Token type: {reader.TokenType}; Object type: {objectType.Name};"
38 );
39 return null;
40 }
41
42 public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
43 {
44 writer.WriteValue(value?.ToString());
45 }
46}