JavaScriptSerializer - JSON serialization of enum as stringAsk Questions

 Posted on 09/25/2019

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" }

Share On: facebook gplus twitter
profile
Asked by Chirag Bhatt on 09/25/2019 Score: 26 points
Add Comment:

Comments

2 Answers

0 Corrected Answers
Aproved Answers
0
Profile
Answered by Praful Chauhan on 9/25/2019 7:49:38 AM Score: 116 points

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.

Edit:  As pointed out by @OmerBakhari JSON.net covers this use case

(via the attribute [JsonConverter(typeof(StringEnumConverter))]) and many others not handled by the built in .net serializers. 

Here is a link comparing features and functionalities of the serializers.

Comments

Add Comment:
Aproved Answers
1
Profile
Answered by Doug Stevenson on 9/25/2019 7:47:11 AM Score: 56 points

I have found that Json.NET provides the exact functionality I'm looking for with a StringEnumConverter attribute:

 

using Newtonsoft.Json;

using Newtonsoft.Json.Converters;

[JsonConverter(typeof(StringEnumConverter))]

public Gender Gender { get; set; }

More details at available on StringEnumConverter documentation.

Comments

Add Comment:

Post Your Answers

Existing Members

Sign in to your account
Email Address
Password
New Member?
Sign up and complete profile
Full Name
Email Address
I have read and agree to the Terms of Service and Privacy Policy
Please subscribe me to the StoodQ newsletters
Guideline to answer a question:

Useful tips to submit your answer
Please read below guidelines before you submit your answer for question.

  • Read and understand question for which you are submitting your answer.
  • Try to avoid grammatical and spell mistake while answering.
  • Do not post any irrelevant information in your answer.
  • Explain your answer with example or any reference link to help who posted question.
  • If you find irrelevant question, please report it to support. Click here to contact support.
  • You agree to the privacy policy and terms of use to submit any contents.

Note: StoodQ is online developers community which helps developer for their difficulty, lets help them with your value contribution.