C# - Web API - Serializing Enums as strings with spaces
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 that.
TheBrogrammer
Updated on June 12, 2022Comments
-
TheBrogrammer almost 2 years
My question is simple, but a little more specific than other questions related to serializing enumerated types as strings.
Consider the following piece of code:
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 may look something like this:
{ "Type" : "TypeTwo" }
My Question: is it possible to send serialized enums as strings with spaces before each capital letter? Such a solution would produce JSON like this:
{ "Type" : "Type Two" }
Let me know if there's any additional information needed to solve my problem. Thanks!
EDIT:
It's preferable if the enums are only converted to strings with spaces while serializing them to JSON. I'd like to exclude spaces while using
MyEnum.ToString()
on the backend.