1

A class that contains an enum property and serializing the object using JavaScriptSerializer. When i serialize the JSON i am getting index value rather the text. As an example:

    public enum LocationType
    {
        [Description("Description 1") ,EnumMember(Value = "EST")]
        EST = 1,
        [Description("Description 2"), EnumMember(Value = "INTNS")]
        INTNS = 2,
        [Description("Description 3"), EnumMember(Value = "INTS")]
        INTS = 3
    }
public class Details
    {
        public LocationType? LocationType { get; set; }
    }

List<Details> obj = new List<Details>();
            obj.Add(new Details() { LocationType = LocationType.INTNS });
            obj.Add(new Details() { LocationType = LocationType.INTS });
            obj.Add(new Details() {  LocationType = LocationType.EST });
            obj.Add(new Details() { LocationType = LocationType.INTS });
            obj.Add(new Details() {  LocationType = LocationType.EST });
            obj.Add(new Details() {  LocationType = LocationType.EST });
            obj.Add(new Details() {  LocationType = LocationType.INTS });
            obj.Add(new Details() {  LocationType = LocationType.EST });

        return obj;

Actual json result:

{ "LocationType ": 2 }

Expected json result:

{ "LocationType ": "INTNS" } 
dbc
  • 104,963
  • 20
  • 228
  • 340
karthik
  • 159
  • 1
  • 12
  • I can't use LocationType.INTNS.Value for Enum. It will return INTNS when using LocationType.INTNS – karthik Oct 23 '17 at 12:05
  • 1
    Use Json.Net it's much better. Even MS themselves have stopped using the JavaScriptSerialzer these days in preference to Json.Net – Liam Oct 23 '17 at 12:10
  • When i using newtonsoft it will working fine as i am expected but i need to achive this case in javascriptserializer – karthik Oct 23 '17 at 12:12

1 Answers1

0

Okay i just tested, and as suspected you are assigning the enum a value twice. if you want to assign it to "string" value instead of and int. You dont need to set it to an int as shown in the article: https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/enumeration-types-in-data-contracts

So if you do it like this it will work:

public enum LocationType
{
    [Description("Description 1") ,EnumMember(Value = "EST")]
    EST,
    [Description("Description 2"), EnumMember(Value = "INTNS")]
    INTNS,
    [Description("Description 3"), EnumMember(Value = "INTS")]
    INTS
}

You might need to call a ToString() on the enum when using the value:

LocationType.INTNS.ToString();