Last active
October 14, 2018 20:23
-
-
Save joaopgrassi/28442b30b7081606c566c8be32098ceb to your computer and use it in GitHub Desktop.
An example of an JsonConverter that converts a Flags enum to an string[]. Also converters string[] and int[] back to Flags enum type. Supports generic types
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