5

Possible Duplicate:
JSON serialization of c# enum as string

I have two classes as follows:

Transaction
    int OrderNumber
    // ... snip ...
    IEnumerable<Item> Items

Item
    string Sku
    // ... snip ...
    ItemCategory Category

ItemCategory is an enum that looks like this:

[DataContract]
public enum ItemCategory
{
    [EnumMember(Value = "Category1")]
    Category1,

    [EnumMember(Value = "Category2")]
    Category2
}

My two classes are decorated with the DataContract and DataMember attributes as appropriate.

I am trying to get a JSON representation of the Transaction item. Within Transaction, I have a public method that looks like this:

public string GetJsonRepresentation()
{
    string jsonRepresentation = string.Empty;

    DataContractJsonSerializer serializer = new DataContractJsonSerializer(this.GetType());
    using (MemoryStream memoryStream = new MemoryStream())
    {
        serializer.WriteObject(memoryStream, this);
        jsonRepresentation = Encoding.Default.GetString(memoryStream.ToArray());   
    }

    return jsonRepresentation;
}

This is returning a string that looks like this:

{
    "OrderNumber":123,
    "Items":[{"SKU": "SKU1","Category": 0}]
}

This is what I want, except for the fact that the "Category" enum value for each Item is being serialized as its integer value, instead of the value I am specifying in the EnumMember attribute. How can I get it so the JSON returned looks like "Category": "Category1" instead of "Category": 0?

Community
  • 1
  • 1
Andrew Keller
  • 3,198
  • 5
  • 36
  • 51

1 Answers1

4

Please take look at JSON serialization of enum as string in stack overflow. No there is no special attribute you can use. JavaScriptSerializer serializes enums to their numeric values and not their string representation. You would need to use custom serialization to serialize the enum as its name instead of numeric value.

Community
  • 1
  • 1
DeveloperX
  • 4,633
  • 17
  • 22
  • 1
    Incorrect, use StringEnumConverter. Specify it using a decorator if you just want it to be a string in a single instance, or include the converter in your serializer settings to globally convert enums to strings and vice versa – wallacer Apr 10 '14 at 21:59
  • 3
    @wallacer @DeveloperX is actually correct. `StringEnumConverter` is a Json.Net attribute, not usable in base .Net – Luke Marlin May 12 '14 at 16:40