我正在为 Stack Exchange API 创建类。 filter_object type 包含一个成员 filter_type
,它将是 safe
、unsafe
或 invalid
。所以我创建了一个这样的枚举:
[JsonConverter(typeof(StringEnumConverter))]
public enum FilterType
{
safe,
@unsafe, // Here lies the problem.
invalid
}
由于 unsafe
是一个关键字,我必须为其添加一些前缀。但是我怎样才能让值“unsafe”自动映射到@unsafe
呢?示例 JSON:
{
"filter": "....",
"filter_type": "unsafe",
"included_fields": [
"...",
"....",
"....."
]
}
我如何反序列化它,以便 filter_type
自动转换为 FilterType.@unsafe
?
更新 - 已解决:
在标识符前使用@符号可以使其与关键字相同。即使 @ 出现在智能感知中,它也能正常工作。
最佳答案
你可以像这样使用 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<MyClass>(json);
var itsUnsafe = myClass.filter_type == FilterType.@unsafe;
Console.WriteLine(itsUnsafe);
}
public static string json = @"{
""filter"": ""...."",
""filter_type"": ""unsafe"",
""included_fields"": [
""..."",
""...."",
"".....""
]
}";
}
输出是:
true
您可以在此处查看示例:https://dotnetfiddle.net/6sb3VY
关于c# - 将某个 JSON 值映射到枚举值 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34212090/