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" } 
3
  • I can't use LocationType.INTNS.Value for Enum. It will return INTNS when using LocationType.INTNS Commented Oct 23, 2017 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 Commented Oct 23, 2017 at 12:10
  • When i using newtonsoft it will working fine as i am expected but i need to achive this case in javascriptserializer Commented Oct 23, 2017 at 12:12

1 Answer 1

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(); 
Sign up to request clarification or add additional context in comments.

2 Comments

This is not a proper solution we need that corresponding index
When i using newtonsoft it will working fine as i am expected but i need to achive this case in javascriptserializer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.