23

Given the following in C#:

[Flags] 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) { stringBuilder.Append( string.Format( @"""{0}"": {1},", Enum.GetName(typeof(Highlights), value), Convert.ChangeType(value, value.GetTypeCode()))); } stringBuilder.Remove(stringBuilder.Length - 1, 1); stringBuilder.Append("}}"); return stringBuilder.ToString(); } 
3
  • 1
    +1, nice code. BTW: s/typeof(Highlights)/type/g Commented Feb 8, 2013 at 15:46
  • 3
    @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. Commented Feb 8, 2013 at 15:46
  • 3
    @ElYusubov: I disagree, the desired output is completely different than the one in the linked question. Commented Feb 8, 2013 at 15:47

2 Answers 2

9
public static class EnumExtensions { public static string EnumToJson(this Type type) { if (!type.IsEnum) throw new InvalidOperationException("enum expected"); var results = Enum.GetValues(type).Cast<object>() .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.

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

1 Comment

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.
6

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

2 Comments

Thanks, I did try that initially with look up values but was having some issues, will have another look.
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)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.