Quantcast
Channel: Web API
Viewing all articles
Browse latest Browse all 4850

Can't get JsonConverter to use ToString() version of enums

$
0
0

Hello,

I have a web API and in one of my actions, I'm trying to send back a json string. I'm trying to built the json string from a bunch of serializable objects. I'm having an issue with enums.

Here are my enums:

public enum ReportCardPerson
{
Unknown = 0,
You = 1,
Others = 2
}

...and here is the object that contains the enum:

public class ReportCardItem
{
public ReportCardPerson Label { get; set; }
public decimal Value { get; set; }
public string ValueColor { get; set; }
}

When I convert my instances of ReportCardItem to json using:

string jsonString = new JavaScriptSerializer().Serialize(reportCardItem);

I get values of 1 and 2 for Label.

What I want are values of "You" and "Others"--that is, the ToString() values.

In my google research on how to solve this problem, I came across this:

[JsonConverter(typeof(StringEnumConverter))]

and this:

[EnumMember(Value = "blah")]

So I rewrote my enums and my class as follows:

public enum ReportCardPerson
{
[EnumMember(Value = "Unknown")]
Unknown = 0,

[EnumMember(Value = "You")]
You = 1,

[EnumMember(Value = "Others")]
Others = 2
}

public class ReportCardItem
{
[JsonConverter(typeof(StringEnumConverter))]
public ReportCardPerson Label { get; set; }
public decimal Value { get; set; }
public string ValueColor { get; set; }
}

But this isn't working. How do I get this to work. Or if I should be going about this in a completely different way, how should I do that?

Thank you.


Viewing all articles
Browse latest Browse all 4850

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>