在枚举参数中使用Dash( - )字符

时间:2022-02-26 16:52:49
public enum TimeFormat
{ 
        @12-hour,
        @24-hour
}

Hi,

嗨,

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

我使用newtonsoft反序列化器将json字符串反序列化为一个对象。

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

JsonDeserializer检查枚举参数名称。如果它与json字符串相同。它将字符串转换为枚举。

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

我可以在枚举中使用Dash,Minus( - )字符作为枚举参数。我尝试使用上面的,但我无法编译项目。

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.

反序列化器无法反序列化json字符串。

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

错误:请求的值'12 -hour'不是foun

1 个解决方案

#1


5  

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.

StringEnumConverter检查EnumMemberAttribute。

#1


5  

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.

StringEnumConverter检查EnumMemberAttribute。