【问题标题】:Receiving data from a database and turning them into a dictionary从数据库接收数据并将其转换为字典
【发布时间】:2022-01-16 23:02:53
【问题描述】:

为什么这个功能不起作用:

   [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;
    }

邮递员投掷: System.NotSupportedException:不支持集合类型“System.Collections.Generic.Dictionary`2[System.Int32,System.String]”。

状态:500 内部服务器错误

但是这个功能确实有效:

  [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;
    }

邮递员给了我我需要的答案

【问题讨论】:

  • 我刚刚测试过。一切正常。你用的是什么序列化器?你能用控制器配置展示你的 API 启动吗
  • IMO int->字符串映射使 JSON 无效,因为字典/对象意味着具有字符串键/标识符。
  • 另一方面,我没有任何确凿的证据表明端点会返回 JSON。

标签: c# dictionary httpclient http-get


【解决方案1】:

我刚刚测试了 var customOutPut = new Dictionary() 字典,Posman 返回了结果

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

我的控制器配置为使用 Newtonsoft.Json,我猜它会自动将 int 转换为字符串以创建有效的 json,

但是这个 json 是无效的

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

这就是您遇到异常的原因。我做了一些研究,发现 System.Text.Json: The collection type ‘System.Collections.Generic.Dictionary[System.Int32,System.String] is not supported 是net core 3.1-5.0的常见问题。但它似乎已经为 net 6 修复了。如果您使用早期版本,建议 Text.Json 创建一个自定义 DictionaryConverter 作为解决方法

但我个人会尝试将此作为解决方法

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

收到数据后,可以将customerId转回int。您的变体 2 可能无法正常工作,因为字典键必须是唯一的。

但如果你尝试获取字典值,它仍然有效,因为它不是 json

var val=  customOutPut[1]; //cust1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-05
    • 2022-07-05
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    相关资源
    最近更新 更多