c# - How to decorate JSON.NET StringEnumConverter -


i'm consuming api returns string values this. some-enum-value

i try put these values in enum, since default stringenumconverter doesn't job try decorate converter additional logic. how can make sure values correctly deserialized?

following code tryout job done. line reader = new jsontextreader(new stringreader(cleaned)); breaking whole thing since base.readjson cant recognize string json.

is there better way of doing without having implement excisting logic in stringenumconverter? how fix 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) => + 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));     } } 

i solved issue adding enummember attributes on enum values. json.net default stringenumconverter deals these attributes.

example:

public enum myenum {     [enummember("some-enum-value")]     someenumvalue,     value,     [enummember("some-other-value")]     someothervalue } 

please note have specify attributes in case of dashes or other special chars can't use in enum. uppercase lowercase dealt stringenumconverter. if service returns value someenumvalue should use in enum someenumvalue. if prefer someenumvalue should use enummember attribute. in case service returns someenumvalue can use someenumvalue (it works out of box when use camelcasetext property).

you can specify converters , other settings in jsonserializersettings.

here example of settings use myself.

new jsonserializersettings {     contractresolver = new camelcasepropertynamescontractresolver(),     converters = new list<jsonconverter> { new stringenumconverter { camelcasetext = true } },     nullvaluehandling = nullvaluehandling.ignore }; 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -