Take the 2-minute tour ×

Given the following in C#:

public enum MyFlags {
  None = 0,
  First = 1 << 0,
  Second = 1 << 1,
  Third = 1 << 2,
  Fourth = 1 << 3

Are there any existing methods in ServiceStack.Text for serializing to the following JSON?

  "MyFlags": {
    "None": 0,
    "First": 1,
    "Second": 2,
    "Third": 4,
    "Fourth": 8

Currently I'm using the routine below, are there better ways to do this?

public static string ToJson(this Type type)
        var stringBuilder = new StringBuilder();
        Array values = Enum.GetValues(type);
        stringBuilder.Append(string.Format(@"{{ ""{0}"": {{", type.Name));

        foreach (Enum value in values)
                    @"""{0}"": {1},", 
                    Enum.GetName(typeof(Highlights), value), 
                    Convert.ChangeType(value, value.GetTypeCode())));

        stringBuilder.Remove(stringBuilder.Length - 1, 1);
        return stringBuilder.ToString();
share|improve this question
+1, nice code. BTW: s/typeof(Highlights)/type/g –  Heinzi Feb 8 '13 at 15:46
@GavinFaux An enum isn't a collection. Enums are like classes with constants, thus I don't find "legal" serializing them as objects or associative arrays. –  Matías Fidemraizer Feb 8 '13 at 15:46
@ElYusubov: I disagree, the desired output is completely different than the one in the linked question. –  Heinzi Feb 8 '13 at 15:47
add comment

2 Answers

up vote 2 down vote accepted

You're better off populating a Dictionary<string,int> or a Typed DTO and serializing that.

share|improve this answer
Thanks, I did try that initially with look up values but was having some issues, will have another look. –  Gavin Faux Feb 8 '13 at 16:29
Sorry for the duplicate, I was looking to see if there was anything already in ServiceStack, which is: Enum.GetValues(typeof(MyEnum)).OfType<MyEnum>().Where(x => x != MyEnum.None).ToDictionary(k => k.ToString(), v => (int)v) –  Gavin Faux Feb 10 '13 at 18:49
add comment
public static class EnumExtensions
    public static string EnumToJson(this Type type)
        if (!type.IsEnum)
            throw new InvalidOperationException("enum expected");

        var results =
                .ToDictionary(enumValue => enumValue.ToString(), enumValue => (int) enumValue);

        return string.Format("{{ \"{0}\" : {1} }}", type.Name, Newtonsoft.Json.JsonConvert.SerializeObject(results));


Using a dictionary of to do the heavy lifting. Then using Newtonsoft's json convert to convert that to json. I just had to do a bit of wrapping to add the type name on.

share|improve this answer
I was working on something like this, but you beat me to it. One modification: You can use the builtin JavaScriptSerializer instead of an external library. See here for example. –  Bobson Feb 8 '13 at 16:31
add comment

Your Answer


