将某个JSON值映射到枚举值C#

我正在为Stack Exchange API创建类。 filter_object类型包含成员filter_type ,该成员将是safeunsafeinvalid 。 所以我创建了一个这样的枚举:

 [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