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"
}
Ideally looking for
answer with built-in .NET framework classes, if not possible alternatives (like
Json.net) are welcome.
class="normal">Answer
No there
is no special attribute you can use. JavaScriptSerializer
serializes enums
to their numeric values and not their string
representation. You would need to use custom serialization to serialize the
enum
as its name instead of numeric
value.
/>
If you can use JSON.Net instead of
JavaScriptSerializer
than see href="https://stackoverflow.com/a/2870420/477420">answer on this question
provided by href="https://stackoverflow.com/users/56829/omer-bokhari">OmerBakhari:
JSON.net covers this use case (via the attribute
[JsonConverter(typeof(StringEnumConverter))]
) and many others
not handled by the built in .net serializers. href="https://www.newtonsoft.com/json/help/html/JsonNetVsDotNetSerializers.htm"
rel="noreferrer">Here is a link comparing features and functionalities of the
serializers.
No comments:
Post a Comment