I have a class that contains an enum
property, and upon serializing the object using JavaScriptSerializer
, my json result contains the integer value of the enumeration rather than its string
"name". Is there a way to get the enum as a string
in my json without having to create a custom JavaScriptConverter
? Perhaps there's an attribute that I could decorate the enum
definition, or object property, with?
As an example:
enum Gender { Male, Female }
class Person
{
int Age { get; set; }
Gender Gender { get; set; }
}
Desired json result:
{ "Age": 35, "Gender": "Male" }
This is an old question but I thought I'd contribute just in case. In my projects I use separate models for any Json requests. A model would typically have same name as domain object with "Json" prefix. Models are mapped using AutoMapper. By having the json model declare a string property that is an enum on domain class, AutoMapper will resolve to it's string presentation.
In case you are wondering, I need separate models for Json serialized classes because inbuilt serializer comes up with circular references otherwise.
Hope this helps someone.
I wasn't able to change the source model like in the top answer (of @ob.), and I didn't want to register it globally like @Iggy. So I combined https://stackoverflow.com/a/2870420/237091 and @Iggy's https://stackoverflow.com/a/18152942/237091 to allow setting up the string enum converter on during the SerializeObject command itself:
@Iggy answer sets JSON serialization of c# enum as string only for ASP.NET (Web API and so).
But to make it work also with ad hoc serialization, add following to your start class (like Global.asax Application_Start)
More information on the Json.NET page
Additionally, to have your enum member to serialize/deserialize to/from specific text, use the
attribute, like this:
ASP.NET Core way:
https://gist.github.com/regisdiogo/27f62ef83a804668eb0d9d0f63989e3e
Not sure if this is still relevant but I had to write straight to a json file and I came up with the following piecing several stackoverflow answers together
It assures all my json keys are lowercase starting according to json "rules". Formats it cleanly indented and ignores nulls in the output. Aslo by adding a StringEnumConverter it prints enums with their string value.
Personally I find this the cleanest I could come up with, without having to dirty the model with annotations.
usage:
For ASP.Net core Just add the following to your Startup Class: