I want to serialize an enum type, so that it returns a array with the enums as a object that contains both the "value", "name" and a data annotation value. I need help with the serialization. Here's what I've done so far: The enum:
public enum Status
{
[Display(Name="Active status")]
Active = 1,
[Display(Name = "Deactive status")]
Deactive = 2,
[Display(Name = "Pending status")]
Pending = 3
}
The DTO Object that should be serialized:
public class ProjectDto
{
public Type StatusEnum { get; set; }
public Status CurrentStatus { get; set; }
}
Assigning of values:
var project = new ProjectDto
{
CurrentStatus = Status.Active,
StatusEnum = typeof (Status)
};
var output = JsonConvert.SerializeObject(project);
To get the values from the enum I use:
Enum.GetNames(typeof(Status)) //To get the names in the enum
Enum.GetValues(typeof(Status)) //To get the values in the enum
To get the data annotation name value is a bit trickier but I found help in this article: http://geeksharp.com/2011/11/02/power-up-your-enumerations/ They've created a helper method that will get the value written in the data annotation using:
public static string GetAttributeValue<T>(this Enum e,
Func<T, object> selector) where T : Attribute
{
var output = e.ToString();
var member = e.GetType().GetMember(output).First();
var attributes = member.GetCustomAttributes(typeof(T), false);
if (attributes.Length > 0)
{
var firstAttr = (T)attributes[0];
var str = selector(firstAttr).ToString();
output = string.IsNullOrWhiteSpace(str) ? output : str;
}
return output;
}
And you can get the value using:
.GetAttributeValue<DisplayAttribute>(y => y.Name)
Output should be something like
{
statusEnum: [
{ "value": "1", "name": "Active", "label": "Active status" },
{ "value": "2", "name": "Deactive", "label": "Deactive status" },
{ "value": "3", "name": "Pending", "label": "Pending status" }
],
currentStatus: { "value": "1", "name": "Active", "label": "Active status" }
}
As mentioned I need help creating the custom Json.NET serialize and deserialize to get the desired output. Any help would be apriciated.
CurrentStatusproperty actually an array? Also, how isStatusEnum, which is of typeSystem.Type, being serialized to an object that looks like that?