How do you serialize an array of enums to an array of Json strings?
Based on Diego's unanswered by the highest voted on this question:
Serializing JSON enum as strings
So for the enumeration:
public enum ContactType
{
Phone = 0,
Email = 1,
Mobile = 2
}
And, for example, for. property:
//could contain ContactType.Phone, ContactType.Email, ContactType.Mobile
IEnumerable<ContactType> AvailableContactTypes {get;set;}
Something like JSON:
{ContactTypes : ['Phone','Email','Mobile']}
instead
{ContactTypes : [0,1,2]}
As is the case with a regular JavaScriptSerializer?
source to share
It looks like one of the more recent versions of Json.NET has a corresponding condition for this using the ItemConverterType
attribute property JsonProperty
as described here:
http://james.newtonking.com/archive/2012/05/08/json-net-4-5-release-5-jsonproperty-enhancements.aspx
I was unable to try it out as I ran into issues when upgrading from Json.NET 3.5 that were related to my own project. In the end, I converted my IEnumerable<string>
viewmodel to as per Schmiddty's suggestion (there is still an impedance mismatch and I will come back to refactor this in the future).
Hope this helps someone else with the same problem!
Usage example:
[JsonProperty(ItemConverterType = typeof(StringEnumConverter))]
IEnumerable<ContactType> AvailableContactTypes {get;set;}
source to share
I've always found it easier to add an extra property in these cases than trying to change the behavior of the json.net parser.
[JsonIgnore]
IEnumerable<ContactType> AvailableContactTypes {get;set;}
IEnumerable<string> AvailableContactTypesString
{
get { return AvailableContactTypes.Select(c => c.ToString()); }
}
Of course, if you need to deserialize, you'll need a setter in this property as well.
set { AvailableContactTypes = value
.Select(c => Enum.Parse(typeof(ContactType), c) as ContactType); }
source to share