【发布时间】:2021-11-05 02:14:40
【问题描述】:
在 appsettings.json 我有未命名的 json:
{
"Items": [
{"fruit": "apple"},
{"fruit": "cherry"},
{"fruit": "tomato"},
{"vegetable": "carrot"},
{"vegetable": "tomato"}
]
}
现在我想把它放在一个元组变量的列表或数组中。我正在寻找最简单的代码(可能是 .net core 2050 大声笑),例如:
public static readonly IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
...
var items = config.GetValue<(string,string)[]>("Items");
var items = config.GetValue<List<(string,string)>>("Items");
什么是简单的解决方案,因为上面的行不起作用。我正在寻找可以替换这部分的东西:“config.GetValue("Items");"
试过了:
(string,string)[] items = config.GetSection("Items")
.GetChildren()
.ToList()
.Select(x => (x.Key,x.Value)).ToArray();
Console.WriteLine($"{items.Length}, {items[1]}"); // 2, (1, )
var items = config.GetValue<List<Dictionary<string,string>>>("Items"); // null
var items = config.GetValue<List<Tuple<string,string>>>("Items"); // null
var items = config.GetValue<List<KeyValuePair<string,string>>>("Items"); // null
var items = config.GetSection("Items")
.GetChildren()
.Select(x => new Tuple<string, string>(x.Key, x.Value));
foreach (var item in items) Console.WriteLine($"({item.Item1},{item.Item2})"); // (0,) (1,)
【问题讨论】:
-
你试过字典而不是元组
config.GetValue<Dictionary<string,string>>("Items"); -
我试过 Dictionary
,但没有成功。 -
字典的问题是它只允许一个键一次。该示例包含多种水果和蔬菜。