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

标签 c# json enums json-deserialization

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

[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/

相关文章:

c# - 如果控件的 Eval 值为 null,则隐藏 div

c# - Paypal 付款 - 500 错误

c# - 如何干净地停止运行 matlab dll 函数的 .NET 线程

javascript - 字符串转json数组

java - 如何使用 Struts 2 gzip ajax 请求?

ruby-on-rails - Postgres : Default for column (string) cannot be cast automatically to type enum

struct - 将 Enum 定义为 Struct(为什么要使用这种语法)

c# - 在代码中使用 this()

java - 使用我的 JSON 文件信息填充数组时出现问题

java - Jooq 3.9 不将 MySQL 列链接到枚举