I consume an API which returns the string values like this:
some-enum-value
I try to put these values in an enum , since the default StringEnumConverter doesn't do what I want, which is to to decorate this Converter with some additional logic.
How can I be sure that the values are deserialized correctly ?
The following code is my tryout to get this job done.
However the line
reader = new JsonTextReader(new StringReader(cleaned));
breaks the whole thing since the base.ReadJson can't recognize the string as a JSON.
Is there a better way to do this without having to implement all the existing logic in a StringEnumConverter?
How could I fix my approach?
public class BkStringEnumConverter : StringEnumConverter { public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.String) { var enumString = reader.Value.ToString(); if (enumString.Contains("-")) { var cleaned = enumString.Split('-').Select(FirstToUpper).Aggregate((a, b) => a + b); reader = new JsonTextReader(new StringReader(cleaned)); } } return base.ReadJson(reader, objectType, existingValue, serializer); } private static string FirstToUpper(string input) { var firstLetter = input.ToCharArray().First().ToString().ToUpper(); return string.IsNullOrEmpty(input) ? input : firstLetter + string.Join("", input.ToCharArray().Skip(1)); } }