Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize C# Enum Definition to Json

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();
    }
like image 469
Gavin Faux Avatar asked Feb 08 '13 15:02

Gavin Faux


People also ask

What is serialization in C?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

What is the use of serialize ()?

The serialize() function converts a storable representation of a value. To serialize data means to convert a value to a sequence of bits, so that it can be stored in a file, a memory buffer, or transmitted across a network.

What is serialization with example?

Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object.


2 Answers

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.

like image 118
Kevin Holditch Avatar answered Oct 16 '22 11:10

Kevin Holditch


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

like image 39
mythz Avatar answered Oct 16 '22 12:10

mythz