Last active
June 1, 2020 20:22
-
-
Save ankitvijay/1c909d72046e0dcc8b08f76a85cae2b0 to your computer and use it in GitHub Desktop.
Newtonsoft - JsonConverterVersion2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Import Newtonsoft.Json | |
public class EnumerationJsonConverter : JsonConverter<Enumeration> | |
{ | |
public override void WriteJson(JsonWriter writer, Enumeration value, JsonSerializer serializer) | |
{ | |
if (value is null) | |
{ | |
writer.WriteNull(); | |
} | |
else | |
{ | |
writer.WriteValue(value.Name); | |
} | |
} | |
public override Enumeration ReadJson(JsonReader reader, | |
Type objectType, | |
Enumeration existingValue, | |
bool hasExistingValue, | |
JsonSerializer serializer) | |
{ | |
return reader.TokenType switch | |
{ | |
JsonToken.Integer => GetEnumerationFromJson(reader.Value.ToString(), objectType), | |
JsonToken.String => GetEnumerationFromJson(reader.Value.ToString(), objectType), | |
JsonToken.Null => null, | |
_ => throw new JsonSerializationException($"Unexpected token {reader.TokenType} when parsing an enumeration") | |
}; | |
} | |
private static Enumeration GetEnumerationFromJson(string nameOrValue, Type objectType) | |
{ | |
try | |
{ | |
object result = default; | |
var methodInfo = typeof(Enumeration).GetMethod( | |
nameof(Enumeration.TryGetFromValueOrName) | |
, BindingFlags.Static | BindingFlags.Public); | |
if (methodInfo == null) | |
{ | |
throw new JsonSerializationException("Serialization is not supported"); | |
} | |
var genericMethod = methodInfo.MakeGenericMethod(objectType); | |
var arguments = new[] { nameOrValue, result }; | |
genericMethod.Invoke(null, arguments); | |
return arguments[1] as Enumeration; | |
} | |
catch (Exception ex) | |
{ | |
throw new JsonSerializationException($"Error converting value '{nameOrValue}' to a enumeration.", ex); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment