6

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?

0

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 @DeveloperX is actually correct. StringEnumConverter is a Json.Net attribute, not usable in base .Net

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.