首页 > 解决方案 > 从 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,)

标签: c#.net-core

解决方案


用于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));

推荐阅读