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.

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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This works! And to clarify my edit, this will only effect JSON serialization. Thank you!
this (stackoverflow.com/a/19768223/530933) might also be helpful. [JsonConverter(typeof(StringEnumConverter))] at the top of the enum

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.