简体   繁体   中英

Mapping a certain JSON value to Enum value C#

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
}

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": [
    "...",
    "....",
    "....."
  ]
}

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.

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:

true

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM