Deserialize json character as enumeration
You don't necessary need a custom JsonConverter
you can use the built in StringEnumConverter
with the combination of the EnumMemberAttribute
(from the System.Runtime.Serialization
assembly).
Without the EnumMemberAttribute
it uses the enum names so Artist, Contemporary, etc so you need to change the names with it to your A,C, etc value.
But it is not the nicest solution because you have to repeat your values two times, but it works:
[JsonConverter(typeof(StringEnumConverter))]public enum CardType{ [EnumMember(Value = "A")] Artist = 'A', [EnumMember(Value = "C")] Contemporary = 'C', [EnumMember(Value = "H")] Historical = 'H', [EnumMember(Value = "M")] Musician = 'M', [EnumMember(Value = "S")] Sports = 'S', [EnumMember(Value = "W")] Writer = 'W'}
This code works perfectly:
CardType[] array = { CardType.Artist, CardType.Contemporary };string s = JsonConvert.SerializeObject(array);var array2 = JsonConvert.DeserializeObject<CardType[]>(s);
Update:
What about out-of-box StringEnumConverter
:
[JsonConverter(typeof(StringEnumConverter))]public CardType Type { get; set; }
You can just add SerializerSettings.Converters.Add(new StringEnumConverter());
to your BrowserJsonFormatter class
public class BrowserJsonFormatter : JsonMediaTypeFormatter{ public BrowserJsonFormatter() { SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); SerializerSettings.Formatting = Formatting.Indented; SerializerSettings.NullValueHandling = NullValueHandling.Ignore; SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); SerializerSettings.Converters.Add(new EmptyToNullConverter()); SerializerSettings.Converters.Add(new StringEnumConverter()); //SerializerSettings.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate; } public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType) { base.SetDefaultContentHeaders(type, headers, mediaType); headers.ContentType = new MediaTypeHeaderValue("application/json"); }}