【问题标题】:Asp.Net Core get json array from appsettings.jsonAsp.Net Core 从 appsettings.json 获取 json 数组
【发布时间】:2019-05-07 13:13:03
【问题描述】:

在检索 appsettings.json 中设置的 json 数组时遇到问题。

使用Configuration.GetSection("xxx").GetChildren()获取json数组时,返回值为null。然后我用下面的方法解决了这个问题,它奏效了。

在 appsettings.json 中:

{
  "EndPointConfiguration": [
    {
      "UserName": "TestUser",
      "Email": "Test@global.com"
    },
    {
      "UserName": "TestUser",
      "Email": "Test@global.com"
    }
  ]
}

然后我创建类:

public class EndPointConfiguration 
{
    public string UserName { get; set; }
    public string Email { get; set; }
}

最后,使用 EndPointConfiguration 类的数组即可:

var endPointConfiguration = Configuration.GetSection("EndPointConfiguration").Get<EndPointConfiguration[]>();

我对 .net 核心很陌生,不知道为什么 Configuration.GetSection().GetChildren() 不能工作。有高手能帮忙解答一下吗?谢谢。

【问题讨论】:

  • getChildren 返回IConfigurationSection 的列表,这是一个由键定义并具有值(docs) 的部分。对象数组不是IConfigurationSection,因为它不包含要引用的字符串键

标签: c# asp.net-core


【解决方案1】:

GetChildren() 方法将返回IEnumerable&lt;IConfigurationSection&gt;,如果使用简单类型(例如字符串列表),这非常有用。例如:

{
  "EndPointUsernames": [
      "TestUser1",
      "TestUser2",
      "TestUser3",
      "TestUser4"
   ]
}

可以很容易地添加到字符串数组中,而无需像你一样定义一个单独的类,例如EndPointConfiguration。从这里你可以简单地调用

string[] userNames = Configuration.GetSection("EndPointUsernames").GetChildren().ToArray().Select(c => c.Value).ToArray();

检索这些值。您在示例中正确地完成了它,因为您将结果强输入到 EndPointConfiguration 对象列表中。

【讨论】:

  • 非常感谢您的解释!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-13
  • 2020-06-11
相关资源
最近更新 更多