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

时间:2023-01-26 13:19:24

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:

我正在为Stack Exchange API创建类。 filter_object类型包含成员filter_type,该成员将是安全的,不安全的或无效的。所以我创建了一个这样的枚举:

[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. But how can I make the value "unsafe" to automatically map to @unsafe? Example JSON:

由于unsafe是一个关键字,我不得不为它添加一些前缀。但是,如何使值“不安全”自动映射到@unsafe?示例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中,它也能正常工作。

1 个解决方案

#1


4  

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

#1


4  

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