如何读取 appSettings.json 中的字符串数组?

Val*_*ini 3 c# arrays configuration json .net-core

我的环境是 VSCode 和 NetCore 2.0。

我需要从我的 appsetting.json 中读取一个状态代码和几对代码/消息。

这是我的 appsettings.json 文件

{
  "http": 
  {
    "statuscode": 200
  },
  "responses": 
  {
    "data": [
      {
        "code": 1,
        "message": "ok"
      },
      {
        "code": 2,
        "message": "erro"
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

我正在加载如下所示的配置文件和数据,但一切都为空:

private readonly IConfiguration _conf;
const string APPSET_SEC = "responses";
const string APPSET_KEY = "data";

public ValuesController(IConfiguration configuration)
{
_conf = configuration;

var section = _conf.GetSection($"{APPSET_SEC}:{APPSET_KEY}");
var responses = section.Get<string[]>();

var someArray = _conf.GetSection(APPSET_SEC).GetChildren().Select(x => x.Value).ToArray();

}
Run Code Online (Sandbox Code Playgroud)

响应和 someArray 都为空。字符串数组似乎无效,但它看起来像一个有效的 Json 字符串数组。我需要修改我的 appsettings 或我的 C# 代码以将“数据”数组加载到变量中吗?

我在 json 文件中尝试了一个更简化的数组

{
    "statuscode": 200,
    "data": [
      {
        "code": 1,
        "message": "ok"
      },
      {
        "code": 2,
        "message": "erro"
      }
    ]
 }
Run Code Online (Sandbox Code Playgroud)

使用代码:

var section = _conf.GetSection($"{APPSET_SEC}");
var responses = section.Get<string[]>();
Run Code Online (Sandbox Code Playgroud)

但我仍然没有快乐

Nko*_*osi 6

string[]当它是对象数组时,您试图将其作为字符串数组获取,

创建一个 POCO 模型以匹配设置

public class ResponseSeting {
    public int code { get; set; }
    public string message { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

并得到一个数组。

所以给出以下appsetting.json

{
  "http": 
  {
    "statuscode": 200
  },
  "responses": 
  {
    "data": [
      {
        "code": 1,
        "message": "ok"
      },
      {
        "code": 2,
        "message": "erro"
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

响应数据将被提取如下

var responses = Configuration
    .GetSection("responses:data")
    .Get<ResponseSeting[]>();
Run Code Online (Sandbox Code Playgroud)