How to serialize an emum to it's member value using DataContractJsonSerializer

Last post 07-04-2009 10:52 PM by johnwsaunders3. 1 replies.

Sort Posts:

  • How to serialize an emum to it's member value using DataContractJsonSerializer

    07-01-2009, 8:06 PM
    • Member
      522 point Member
    • auschucky
    • Member since 09-16-2002, 9:48 PM
    • Posts 131

    Hi,

    I'm trying to serialize (and deserialize) an enum to it's member value, not an integer.  This technique is mentioned in this microsoft article http://msdn.microsoft.com/en-us/library/aa347875.aspx but it dosen't work.

    Does anyone know how to do it?

    Here is some sample code

        [DataContract]
        public class Car
        {
            [DataMember]
            public string model;
            [DataMember]
            public CarConditionEnum condition;
        }
    
        [DataContract(Name = "CarCondition")]
        public enum CarConditionEnum
        {
            [EnumMember]
            New,
            [EnumMember]
            Used,
            [EnumMember]
            Rental,
            Broken,
            Stolen
        }
    
        class Program
        {
            public static string SerialiseJSON<E>(E obj)
            {
                MemoryStream memoryStream = new MemoryStream();
                SerialiseJSON<E>(memoryStream, obj);
                return Encoding.Default.GetString(memoryStream.ToArray());
            }
    
            public static void SerialiseJSON<E>(Stream stream, E obj)
            {
                DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(E));
                dataContractJsonSerializer.WriteObject(stream, obj);
            }
    
            static void Main(string[] args)
            {
                Car car = new Car();
                car.condition = CarConditionEnum.New;
                car.model = "Holden";
    
                string JSON = SerialiseJSON<Car>(car);
                Console.Write(JSON);
            }
        }


    Output is:

    {"condition":0,"model":"Holden"}

    Expected Output:

    {"condition":"New","model":"Holden"}


    Thanks,


    Auschucky

  • Re: How to serialize an emum to it's member value using DataContractJsonSerializer

    07-04-2009, 10:52 PM
    Answer

    It looks like it should output "New". As an experiment, try that with the DataContrractSerializer, just so we can see if the problem is specific to JSON.

    John Saunders
Page 1 of 1 (2 items)