19

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.

TheBrogrammer
  • 336
  • 1
  • 3
  • 13
  • 1
    Does adding an EnumMemberAttribute `[EnumMember("Type Two")]` do anything? The source for StringEnumConverter on github appears to take advantage of it. – Paul Abbott Jul 30 '15 at 21:38
  • I'm not sure, but do you think using that attribute will have an effect on each `MyEnum.ToString()` method? – TheBrogrammer Jul 30 '15 at 21:58

1 Answers1

31

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.

carlin.scott
  • 6,214
  • 3
  • 30
  • 35
JGV
  • 5,037
  • 9
  • 50
  • 94
  • This works! And to clarify my edit, this will _only_ effect JSON serialization. Thank you! – TheBrogrammer Jul 30 '15 at 22:26
  • 1
    this (http://stackoverflow.com/a/19768223/530933) might also be helpful. [JsonConverter(typeof(StringEnumConverter))] at the top of the enum – owen gerig Jan 04 '17 at 21:16