[英]Mapping a certain JSON value to Enum value C#
I am creating classes for the Stack Exchange API. 我正在为Stack Exchange API创建类。 The filter_object type contains a member filter_type
which will be either safe
, unsafe
, or invalid
. filter_object类型包含成员filter_type
,该成员将是safe
, unsafe
或invalid
。 So I created an enum like this: 所以我创建了一个这样的枚举:
[JsonConverter(typeof(StringEnumConverter))]
public enum FilterType
{
safe,
@unsafe, // Here lies the problem.
invalid
}
Since unsafe
is a keyword, I had to add some prefix to it. 由于unsafe
是一个关键字,我不得不为它添加一些前缀。 But how can I make the value "unsafe" to automatically map to @unsafe
? 但是,如何使值“不安全”自动映射到@unsafe
? Example JSON: 示例JSON:
{
"filter": "....",
"filter_type": "unsafe",
"included_fields": [
"...",
"....",
"....."
]
}
How can I deserialize it, such that the filter_type
is automatically converted to FilterType.@unsafe
? 我如何反序列化它,以便filter_type
自动转换为FilterType.@unsafe
?
Update - Solved: 更新 - 解决:
Using the @ symbol before an identifier makes it possible to be the same as keywords. 在标识符之前使用@符号可以使其与关键字相同。 It works fine even though the @ appears in intellisense. 即使@出现在intellisense中,它也能正常工作。
You can use JsonProperty, like this 您可以像这样使用JsonProperty
public enum FilterType
{
safe,
[JsonProperty("unsafe")]
@unsafe, // Here lies the problem.
invalid
}
And then it will work properly 然后它将正常工作
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"": [
""..."",
""...."",
"".....""
]
}";
}
The output is: 输出是:
true 真正
You can see example working here: https://dotnetfiddle.net/6sb3VY 您可以在此处查看示例: https : //dotnetfiddle.net/6sb3VY
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.