C # - Web API - Serialization of enumerations as strings with spaces

My question is simple, but a little more specific than other issues related to serializing enumerated types as strings.

Consider the following code snippet:

using Newtonsoft.Json; using Newtonsoft.Json.Converters; public enum MyEnum { TypeOne, TypeTwo, TypeThree } public class Foo { [JsonConverter(typeof(StringEnumConverter))] public MyEnum Types { get; set; } } 

When the web API controller sends serialized Foo objects, they might look something like this:

 { "Type" : "TypeTwo" } 

My question is: is it possible to send serialized enumerations in the form of strings with spaces before each capital letter? Such a solution would create JSON as follows:

 { "Type" : "Type Two" } 

Let me know if there is any additional information needed to solve my problem. Thanks!

EDIT:

This is preferable if the enumerations only convert to strings with spaces, and serialize them to JSON. I would like to eliminate spaces using MyEnum.ToString() on the server.

+7
json enums c # serialization asp.net-web-api
source share
2 answers

Try adding EnumMember as shown below.

 [JsonConverter(typeof(StringEnumConverter))] public enum MyEnum { [EnumMember(Value = "Type One")] TypeOne, [EnumMember(Value = "Type Two")] TypeTwo, [EnumMember(Value = "Type Three")] TypeThree } 

You may need to install a package called System.Runtime.Serialization.Primitives from Microsoft to use it.

+13
source share

I believe that you can add a description attribute to your Enums and try to extract this for serialization. Check out this SO answer . Hope this helps.

 public enum MyEnum { [Description("Type One")] TypeOne, [Description("Type Two")] TypeTwo, ... } 
-one
source share

All Articles