【发布时间】: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<Dictionary<string, string>>。没有什么能阻止数据看起来像{ "A": "Alpha" }, { "A": "Alpha", "B": "Bravo" }, { "B": "Bravo" }。所以它不是KeyValuePair<string, string>,而是一个完整的字典。 -
Letters是一个数组,而不是字典。它包含属性名为A、B、C等的元素,因此不能将其反序列化为属性名为Key和Value的KeyValuePair类。字典是"Letters": { "A":"Alpha","B":"Bravo",...}
标签: c# json .net-core appsettings