【问题标题】:asp.net core ioptions with a dictionary带有字典的 asp.net 核心 ioptions
【发布时间】:2021-06-28 09:16:59
【问题描述】:

我正在尝试从 appsettings.json 文件中将 Letters 读取为 Dictionary。我的 json 包含:

    "Words": [
      "Alpha",
      "Beta",
      "Gama"
    ],
    "Letters": [
      { "A": "Alpha" },
      { "B": "Bravo" },
      { "C": "Charlie" }
    ],

我使用配置类:

public class AppSettingsConfiguration
{
    public List<string> Words { get; set; } = default!;
    public Dictionary<string, string> Letters { get; set; } = default!;
}

property Words 已更正从 .json 读取,但 Letters 抛出异常 'Cannot create instance of type 'System.String' 因为它缺少公共无参数构造函数。 '

如果我尝试过

List<(string, string)> Letters { get; set; }
or
List<KeyValuePair<string, string>> Letters { get; set; }

我得到了所有 3 行,但都是空的 - (null, null)

什么是阅读字典的正确属性?

【问题讨论】:

  • 可悲的是,匹配此数据的模型是 List&lt;Dictionary&lt;string, string&gt;&gt;。没有什么能阻止数据看起来像{ "A": "Alpha" }, { "A": "Alpha", "B": "Bravo" }, { "B": "Bravo" }。所以它不是KeyValuePair&lt;string, string&gt;,而是一个完整的字典。
  • Letters 是一个数组,而不是字典。它包含属性名为ABC 等的元素,因此不能将其反序列化为属性名为KeyValueKeyValuePair 类。字典是"Letters": { "A":"Alpha","B":"Bravo",...}

标签: c# json .net-core appsettings


【解决方案1】:

字典在 C# 中的序列化方式不同。请参阅以下 JSON:

"Letters": {
  "A": "Alpha",
  "B": "Bravo",
  "C": "Charlie"
}

【讨论】:

    【解决方案2】:

    可悲的是,与此数据匹配的模型是 List&lt;Dictionary&lt;string, string&gt;&gt;
    没有什么能阻止数据看起来像:

    {
        "Words": [
            "Alpha",
            "Beta",
            "Gama"
        ],
        "Letters": [
            { "A": "Alpha" }, 
            { "A": "Alpha", "B": "Bravo" },
            { "B": "Bravo" }
        ]
    }
    

    所以它不是KeyValuePair&lt;string, string&gt;,而是一个完整的字典。

    如果你想回到List&lt;KeyValuePair&lt;string, string&gt;&gt;,你可以使用一个简单的SelectMany(x=&gt; x)

    现场演示:https://dotnetfiddle.net/CFtWm3

    【讨论】:

      猜你喜欢
      • 2017-08-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-02
      • 2017-07-17
      • 2018-10-05
      • 2021-11-09
      • 2019-01-26
      • 1970-01-01
      相关资源
      最近更新 更多