4

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.

Fᴀʀʜᴀɴ Aɴᴀᴍ
  • 6,131
  • 5
  • 31
  • 52
  • You can also use uppercase like you do for class names etc in C#. And add a camelcase converter, see [this question](http://stackoverflow.com/questions/28552567/web-api-2-how-to-return-json-with-camelcased-property-names-on-objects-and-the) – huysentruitw Dec 10 '15 at 22:01
  • So you unaccept my answer, thats really nice :D – Alberto Monteiro Dec 21 '15 at 16:43
  • @AlbertoMonteiro That was not the correct answer. Even if unmapped, if the names are correct, it will automatically get parsed as the correct enum. The problem was that `unsafe` is a keyword. I already came across prefixing @ so that a keyword can be used as an identifier. It appeared in intellisense and so I thought it was not working. But on testing I found it was correct. Seeing that there were no other answers, I accepted yours. However, that's not what is done. So I unaccepted it and edited my question to include the solution. I don't see any wrong in it. – Fᴀʀʜᴀɴ Aɴᴀᴍ Dec 21 '15 at 18:17
  • @AlbertoMonteiro And i would have downvoted it because it was not the correct solution but the vote is locked. The JsonProperty maps to properties, not values. Because it already contained the @, it worked. Try it with `_unsafe`. Your method will throw an exception. – Fᴀʀʜᴀɴ Aɴᴀᴍ Dec 21 '15 at 18:29

1 Answers1

6

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

Alberto Monteiro
  • 5,989
  • 2
  • 28
  • 40