Serializing Multiple Enum Values in WebApi
asp.net-web-api, c#, enums, json, json.net
Solution
I'm an idiot.
"Brown,+Blue"
Is all that was needed.
Problem
If I have an Enum like this: ``` [Flags] public enum EyeColor { All = 1, Brown = 2, Blue = 4, Hazel = 8, Green = 16 } ``` And then return a JSON result like this: ``` jsonBody.EyeColor = EyeColor.Brown | EyeColor.Blue; ``` I see the following in my jsonBody on the client: ``` "Brown, Blue" ``` However if I send the above string to WebAPI via an EyeColor property: ``` var eyeColor = "Brown, Blue" var query = '?Index=1&EyeColor=` + eyeColor; // send json GET request and use [FromUri] to extract ``` Serverside, I get: ``` dto.EyeColor: 0 ``` Though if I do this: ``` var eyeColor = "All" var query = '?Index=1&EyeColor=` + eyeColor; // send json GET request and use [FromUri] to extract ``` I get ``` dto.EyeColor: All ``` So what I'm wondering is - in the event where I want to not only retrieve a string-serialized Enum from WebApi, but also send a string to represent multiple Enums that have been selected (and deserialized into multiple enums), what do I need to do? My Global.asax: ``` JsonSerializerSettings jSettings = new JsonSerializerSettings(); jSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter()); GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = jSettings; GlobalConfiguration.Configuration .Formatters .JsonFormatter .SerializerSettings .ContractResolver = new CamelCasePropertyNamesContractResolver(); ```