1

Suppose I have an enum

public enum Countries {
    France, GreatBritain, Japan, CostaRica, ...
}

And suppose I have the following action in WebApi Controller

[HttpGet]
public ActionResult<Dictionary<Countries, int> Get() {
   return new Dictionary<Countries, int> {
      [Countries.France] = 10,
      [Countries.CostaRica] = 50
      ...
   }
}

JSON that goes to the client is "France": 10, "CostaRica": 50, etc.

I would very much prefer to have 0: 10, 4: 50 instead. Client has no knowledge of the enum values; only the integer index and description (like "France" or "Costa Rica"). I am seeding the database using same enum - so I am confident that IDs match.

I tried different JsonConverter options, but they all seem to assume scalar value.

Note: this is a simplified example; real business application is much more complex. Obviously, there is a big benefit to use enum on the server without creating Dictionary<int, int> and casting all keys before returning to client. I am pretty sure Json.NET can convert it - I just can figure how to help it.

My application is .NET Core 2.2; so is this example. I know that 3.0 handles Json.Net slightly differently; but I don't think this converting issue is version-dependent

6
  • With int values you have to cross fingers that the ids will match. With strings you know that they will match.
    – Sir Rufo
    Mar 1, 2020 at 11:25
  • As I said, I seed the same enums in the database. So, I know that they match :) The problem that the client doesn't have visibility to the strings
    – Felix
    Mar 1, 2020 at 11:27
  • There's an example in the documentation: Sample factory pattern converter: The following code shows a custom converter that works with Dictionary<Enum,TValue>. The code follows the factory pattern because the first generic type parameter is Enum and the second is open.
    – dbc
    Mar 1, 2020 at 16:31
  • thank you, @dbc! I was hoping that I can use one of the "built-in" converters out of the box; but it looks like the answer is "Nope - you need to write your own". If you want to convert (ha-ha) your comment to an answer - I'll accept it.
    – Felix
    Mar 1, 2020 at 18:59
  • 1
    @dbc - you are correct. In .Net 3.0 I simply used services.AddControllers().AddNewtonsoftJson(); at least for now to not get distracted
    – Felix
    Mar 1, 2020 at 19:28

1 Answer 1

2

It's a matter of casting to int, and return the ActionResult<Dictionary<int, int>> which would be something like this :

[HttpGet]
public ActionResult<Dictionary<int, int>> Get() {
   return new Dictionary<Countries, int> {
      [Countries.France] = 10,
      [Countries.CostaRica] = 50
      ...
   }.ToDictionary(x => (int)x.Key, x => x.Value);
}

UPDATE

Just want to share this, if you need to convert any Enum to a Dictionary using Reflection, you can do something like this :

public Dictionary<string, object> GetEnumAsDictionary<TEnum>() where TEnum : System.Enum
{
    var result = new Dictionary<string, object>();

    var _fields = typeof(TEnum).GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);

    for (int i = 0; i < _fields.Length; i++)
    {
        result.Add(_fields[i].Name, _fields[i].GetRawConstantValue());
    }

    return result;
}

usage :

var enDic = GetEnumAsDictionary<Countries>();

GetRawConstantValue returns object that's why I made the dictionary value type as an object. but it's easy to bind it to other datatypes or making it generic.

I thought this would be useful to share.

3
  • As I mention in the question, that's exactly what I want to avoid (also, I am fine with default values; so not sure what's the purpose of manually overriding)
    – Felix
    Mar 1, 2020 at 11:44
  • Actually, on the second thought, casting to Dictionary<int, int> (or really, Dictionary<string, int> because the values get quoted, seems to be the best and easiest solution. Thank you!
    – Felix
    Mar 1, 2020 at 19:31
  • @Felix, I have updated my answer with a way to convert enum to a dictionary.
    – iSR5
    Mar 2, 2020 at 0:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.