Search code examples
c#dictionaryhttpclienthttp-get

Receiving data from a database and turning them into a dictionary


Why this function does not work:

   [HttpGet("getCustomerAsDict")]
    public async Task<object> GetCustomersAsDict()
    {
        var customOutPut = new Dictionary<int, string>();
        var customer = await _context.Customers.ToListAsync();
        foreach (var custom in customer)
        {
            customOutPut[custom.CustomerId] = custom.CustomerName;
        }
        return customOutPut;
    }

Postman throw: System.NotSupportedException: The collection type 'System.Collections.Generic.Dictionary`2[System.Int32,System.String]' is not supported.

status: 500 Internal Server Error

But this function does work:

  [HttpGet("getCustomerAsDict")]
    public async Task<object> GetCustomersAsDict()
    {
        var customOutPut = new Dictionary<string, int>();
        var customer = await _context.Customers.ToListAsync();
        foreach (var custom in customer)
        {
            customOutPut[custom.CustomerName] = custom.CustomerId;
        }
        return customOutPut;
    }

And Postman gives me the answer I needed


Solution

  • I just tested var customOutPut = new Dictionary<int, string>() dictionary and Posman returned the result

    {
        "1": "cust1",
        "2": "cust2"
    }
    

    my controllers are configured to use Newtonsoft.Json and I guess it automatically converts int to string to create a valid json,

    But this json is not valid

    {
        1: "cust1",
        2: "cust2"
    }
    

    this is why you got an exception. I made some research and found that System.Text.Json: The collection type ‘System.Collections.Generic.Dictionary[System.Int32,System.String]is not supported is the common for net core 3.1-5.0. But it seems it is already fixed for net 6. If you use the earlier versions, it is recomended for Text.Json to create a custom DictionaryConverter as work around

    but I personally would try this as a work around

    var customOutPut = new Dictionary<string, string>();
         
    foreach (var custom in customer)
      customOutPut.Add(custom.CustomerId.ToString(), custom.CustomerName);
    

    after receiving data , you can convert customerId back to int. Your variant 2 maybe is not working properly, since a dicitionay key must be unique.

    But if you try to get a dictionary value, it is still valid since it is not a json

    var val=  customOutPut[1]; //cust1