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
58.5k26 gold badges100 silver badges151 bronze badges
asked Jan 24, 2013 at 15:43
2
  • Just add another property that returns the string version of the enum. Commented Jan 24, 2013 at 15:57
  • 2
    stackoverflow.com/questions/2441290/… Commented Jan 24, 2013 at 15:57

3 Answers 3

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.

answered Jan 24, 2013 at 15:58
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

answered Jan 24, 2013 at 15:56
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
}
answered Jan 24, 2013 at 15:58

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.