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

时间:2018-07-24 00:25:56

标签: c# arrays json configuration .net-core

我的环境是VSCode和NetCore 2.0。

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

这是我的appsettings.json文件

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

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

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#代码以将“数据”数组加载到变量中吗?

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

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

使用代码:

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

但我仍然没有喜悦

2 个答案:

答案 0 :(得分:2)

您正在尝试将其作为对象数组时以字符串数组string[]的形式获取

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

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

答案 1 :(得分:-1)

这可以在Java中使用具有保证功能的库完成

JSON.body(“ http.statuscode”)->将获得状态码

JSON.body(responses.data.code[0]) --> will get the response code
JSON.body(responses.data.message[0])---> will get the response message
JSON.body(responses.data.code[1])
JSON.body(responses.data.message[1])

关于VScode的工作原理尚无定论。长话短说,这可能对您有帮助!