映射一定的JSON值枚举值C# [英] Mapping a certain JSON value to Enum value C#

查看:229
本文介绍了映射一定的JSON值枚举值C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了堆栈交易所API类。该 filter_object 类型包含成员 FILTER_TYPE 这将是要么安全不安全无效。所以,我创建了一个这样的枚举:

I am creating classes for the Stack Exchange API. The filter_object type contains a member filter_type which will be either safe, unsafe, or invalid. So I created an enum like this:

[JsonConverter(typeof(StringEnumConverter))]
public enum FilterType
{
    safe,
    @unsafe, // Here lies the problem.
    invalid
}



由于不安全是一个关键字,我有一些前缀添加到它。但是,我怎么能值不安全自动映射到 @unsafe ?例如JSON:

Since unsafe is a keyword, I had to add some prefix to it. But how can I make the value "unsafe" to automatically map to @unsafe? Example JSON:

{
  "filter": "....",
  "filter_type": "unsafe",
  "included_fields": [
    "...",
    "....",
    "....."
  ]
}

如何反序列化,使得 FILTER_TYPE 自动转换为过滤式。@不安全

How can I deserialize it, such that the filter_type is automatically converted to 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.

推荐答案

您可以使用JsonProperty,像这样

You can use JsonProperty, like this

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:

真正

您可以看到的例子在这里工作:的 https://dotnetfiddle.net/6sb3VY

You can see example working here: https://dotnetfiddle.net/6sb3VY

这篇关于映射一定的JSON值枚举值C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆