[英]Mapping a certain JSON value to Enum value C#
我正在为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<MyClass>(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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.