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?
-
Just add another property that returns the string version of the enum.Roland Mai– Roland Mai2013年01月24日 15:57:32 +00:00Commented Jan 24, 2013 at 15:57
-
2stackoverflow.com/questions/2441290/…adt– adt2013年01月24日 15:57:58 +00:00Commented Jan 24, 2013 at 15:57
3 Answers 3
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.
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
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
}
Explore related questions
See similar questions with these tags.