c# - 从 appsettings.json 获取一组未命名的 json 元组
问题描述
在 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<(string,string)[]>("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,)
解决方案
用于Configuration.GetSection(string)
先获取键对应的值,然后从子值Items
构造一个。IEnumerable<Tuple<string,string>>
ConfigurationSection section = config.GetSection("Items");
var data = section
.GetChildren()
.Select(x => new Tuple<string, string>(x.Key, x.Value));
推荐阅读
- javascript - 用于将文件上传到 S3 的 Amazon S3 putobject,不返回承诺
- python - django api如何上传多张图片
- f# - 递归联合类型和列表
- python - 如何从 csv 文件而不是列表中获取字符串?
- docker - Gcloud 实例没有 Docker Hub RateLimit
- angular - 找不到名称“StripeCheckoutStatic”?
- android - 我希望能够使用 DrawerHeader 处的 Switch 更改暗/亮模式
- discord.py - 如何在 discord.py 中检查消息是否由机器人发送?
- flutter - 在 Flutter 中从 Firebase Firestore 中检索数据
- groovy - 为什么在无头模式下运行 Fiji/Imagej 时,参数会从上一次缓存?