Skip to content

Instantly share code, notes, and snippets.

@joaopgrassi
Last active October 14, 2018 20:23
Show Gist options
  • Save joaopgrassi/28442b30b7081606c566c8be32098ceb to your computer and use it in GitHub Desktop.
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
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