Last active
October 14, 2018 20:24
-
-
Save joaopgrassi/ef47d4c807cfd2c2ddf94b3b820cd37d to your computer and use it in GitHub Desktop.
An example of a JsonConverter that converts a Flags Enum to a string[]. Also converters string[] and int[] back to Flags Enum type. Supports generics.
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
public class FlagsEnumToStringArrayJsonConverter<T> : JsonConverter | |
where T: struct | |
{ | |
public override bool CanConvert(Type objectType) | |
{ | |
return objectType.IsEnum && objectType.GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0; | |
} | |
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) | |
{ | |
if (reader.TokenType != JsonToken.StartArray) | |
return null; | |
var values = serializer.Deserialize<string[]>(reader).AsEnumerable(); | |
foreach (var item in values) | |
{ | |
if (!Enum.TryParse<T>(item, ignoreCase: true, result: out var result)) | |
return null; | |
} | |
return values | |
.Select(x => Enum.Parse(objectType, x, ignoreCase: true)) | |
.Aggregate(0, (current, value) => current | (int)value); | |
} | |
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) | |
{ | |
if (value == null) | |
{ | |
writer.WriteNull(); | |
return; | |
} | |
var flagsStringArray = Enum.GetValues(value.GetType()) | |
.Cast<int>() | |
.Where(intValue => (intValue & (int)value) == intValue) | |
.Select(intValue => Enum.ToObject(value.GetType(), intValue).ToString().ToLowerInvariant()) | |
.ToArray(); | |
serializer.Serialize(writer, flagsStringArray); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment