如何在appSettings.json中读取字符串数组? [英] How to read a string array in appSettings.json?

查看:530
本文介绍了如何在appSettings.json中读取字符串数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的环境是VSCode和NetCore 2.0.

My env is VSCode and NetCore 2.0.

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

I need to read a status code and several pairs of code/message from my appsetting.json.

这是我的appsettings.json文件

This is my appsettings.json file

{
  "http": 
  {
    "statuscode": 200
  },
  "responses": 
  {
    "data": [
      {
        "code": 1,
        "message": "ok"
      },
      {
        "code": 2,
        "message": "erro"
      }
    ]
  }
}

我正在像下面那样加载配置文件和数据,但是一切都为空:

I'm loading the configuration file and data like below, but everything is null:

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();

}

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

Either responses and someArray are null. It appears that the string array is not valid but it looks like a valid Json string array. What do I need to modify my appsettings or my C# code to get "data" array loaded into the variable?

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

I tryed a more simplificated array in json file

{
    "statuscode": 200,
    "data": [
      {
        "code": 1,
        "message": "ok"
      },
      {
        "code": 2,
        "message": "erro"
      }
    ]
 }

使用代码:

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

但我仍然没有喜悦

推荐答案

当您尝试将其作为对象数组时,将其作为字符串数组string[]

You are trying to get it as a string array string[] when it is an object array,

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

Create a POCO model to match the setting

public class ResponseSeting {
    public int code { get; set; }
    public string message { get; set; }
}

并得到一个数组.

因此,给出以下 appsetting.json

{
  "http": 
  {
    "statuscode": 200
  },
  "responses": 
  {
    "data": [
      {
        "code": 1,
        "message": "ok"
      },
      {
        "code": 2,
        "message": "erro"
      }
    ]
  }
}

响应数据将被提取

var responses = Configuration
    .GetSection("responses:data")
    .Get<ResponseSeting[]>();

这篇关于如何在appSettings.json中读取字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆