Not logged in - Login

Serialize Enum values with JSON structure

The following illustrates how to set up an Enum property so that the enum value name is serialized.
Note: This requires the assembly 'System.Runtime.Serialization' to be added to the project references.

[DataContract]
public class Appointment
{
   [DataMember]
   public int id { get; set; }

   // this property is exposed as a public memeber
   public enAppointmentStatus status { get; set; }
   // this property is the one that is serialized
   [DataMember(Name = "status"]
   public string status_serialized
   {
      get { return Enum.GetName(typeof(enAppointmentStatus), this.status); }
      set { this.status = (enAppointmentStatus)Enum.Parse(typeof(enAppointmentStatus), value); }
   }
}

// our sample Enum
[DataContract(Name = "AppointmentStatus")]
public enum enAppointmentStatus
{
   [EnumMember(Value = "booked")]
   booked,
   [EnumMember(Value = "needs_time")]
   needs_time,
   [EnumMember(Value = "pending")]
   pending,
   [EnumMember(Value = "cancelled")]
   cancelled,
   [EnumMember(Value = "no_show")]
   no_show,
   [EnumMember(Value = "late")]
   late,
   [EnumMember(Value = "drop")]
   drop
}