3

I created a ASP.NET MVC 4 Web application. Within this application i implemented several rest webservices and here comes my question: Is it possible to force the object serialization to use the enum entity names instead of their values?

This is my enum:

    public enum ReturnCode { OK, InvalidParameter }

This is what I get:

{
   "returnCode": 0,
   "data": null
}

But this is what I want:

{
   "returnCode": OK,
   "data": null
}

Is there a way to achieve this?

tereško
  • 57,247
  • 24
  • 95
  • 149
gosua
  • 987
  • 3
  • 13
  • 27

3 Answers3

4

You can use a JsonConverter.

There is a native one for JSON.Net StringEnumConverter mentioned in this question JSON serialization of enum as string

Either anotate your property:

[JsonConverter(typeof(StringEnumConverter))]
public enum ReturnCode { OK, InvalidParameter }

Or use the config examples in WebApi Json.NET custom date handling to register in the global serialiser settings.

Community
  • 1
  • 1
Mark Jones
  • 12,018
  • 2
  • 47
  • 61
0

Difficult to make a suggestion without better understanding of your usage patterns...but none the less.

Make the enum a private field.

Built a public string property with a getter which returns the entity name of the private enum field and a setter which uses Enum.Parse to set the private field value

keithwarren7
  • 13,866
  • 8
  • 50
  • 73
0

Yes you can do that. You need to declare additional string property and use it when serializing/deserializing.

Example:

[DataContract]
public class MyResource
{
    [DataMember]
    public string Data { get; set; }

    public ReturnCode Code { get; set; }

    [DataMember(Name = "returnCode")]
    string ReturnCodeString
    {
        get { return this.Code.ToString(); }
        set
        {
            ReturnCode r;
            this.Code = Enum.TryParse(value, true, out r) ? r : ReturnCode.OK;
        }
    }
}

So now you can pass the value of enum as a string (in both direction from server and from client) i.e.:

{
   "returnCode": "OK",
   "data": null
}

or

{
   "returnCode": "InvalidParameter",
   "data": null
}
Filip W
  • 26,907
  • 6
  • 92
  • 82