我正在为Stack Exchange API创建类.所述filter_object类型包含一个成员filter_type
,其将或者safe
,unsafe
或invalid
.所以我创建了一个这样的枚举:
[JsonConverter(typeof(StringEnumConverter))] public enum FilterType { safe, @unsafe, // Here lies the problem. invalid }
既然unsafe
是关键字,我必须为它添加一些前缀.但是如何使值"不安全"自动映射到@unsafe
?示例JSON:
{ "filter": "....", "filter_type": "unsafe", "included_fields": [ "...", "....", "....." ] }
如何反序列化它,以便filter_type
自动转换为FilterType.@unsafe
?
更新 - 解决:
在标识符之前使用@符号可以使其与关键字相同.即使@出现在intellisense中,它也能正常工作.
您可以像这样使用JsonProperty
public enum FilterType { safe, [JsonProperty("unsafe")] @unsafe, // Here lies the problem. invalid }
然后它将正常工作
class MyClass { public FilterType filter_type { get; set; } } public class Program { public static void Main() { var myClass = JsonConvert.DeserializeObject(json); var itsUnsafe = myClass.filter_type == FilterType.@unsafe; Console.WriteLine(itsUnsafe); } public static string json = @"{ ""filter"": ""...."", ""filter_type"": ""unsafe"", ""included_fields"": [ ""..."", ""...."", ""....."" ] }"; }
输出是:
真正
您可以在此处查看示例:https://dotnetfiddle.net/6sb3VY