13
public enum TimeFormat
{ 
        @12-hour,
        @24-hour
}

Hi,

I use newtonsoft deserializer for deserialize json string to an object.

JsonDeserializer checks enum parameter name. if it's same with json string. it converts string to enum.

Can I use Dash,Minus (-) character in an enum as enum parameter. I tried to use as above, But I couldn't compile project.

Then I tried this.

[JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
public enum TimeFormat
{
    [JsonProperty("12-hour")]
    hour12,
    [JsonProperty("24-hour")]
    hour24,

}

Deserializer couldn't deserialize json string.

Error : Requested value '12-hour' was not foun

halit
  • 1,128
  • 1
  • 11
  • 27
  • http://stackoverflow.com/questions/2441290/json-serialization-of-c-sharp-enum-as-string – Sten Petrov Feb 25 '13 at 14:57
  • @StenPetrov I use StringEnumConverter to deserialize and serialize an enum. But It ignores JsonPropertyAttribute of enum parameters. There is no documentation about it. Why it doesn't checks attribute of enum parameter :( http://james.newtonking.com/projects/json/help/index.html?topic=html/T_Newtonsoft_Json_Converters_StringEnumConverter.htm – halit Feb 25 '13 at 15:09
  • Isn't it something like 'PropertyName'? – Chris Pfohl Feb 25 '13 at 15:14
  • http://stackoverflow.com/questions/2546138/deserializing-json-data-to-c-sharp-using-json-net – Chris Pfohl Feb 25 '13 at 15:15

1 Answers1

12

I fixed issue.

[JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]    
public enum TimeFormat
{
    [System.Runtime.Serialization.EnumMember(Value = "12-hour")]
    hour12,
    [System.Runtime.Serialization.EnumMember(Value = "24-hour")]
    hour24,

}

StringEnumConverter checks EnumMemberAttribute.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
halit
  • 1,128
  • 1
  • 11
  • 27