【问题标题】:How to read a string array in appSettings.json?如何读取 appSettings.json 中的字符串数组?
【发布时间】:2018-12-31 11:58:37
【问题描述】:

我的环境是 VS Code 和 .NET Core 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();
}

response 和 someArray 都为空。字符串数组似乎无效,但它看起来像一个有效的 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[]>();

但我仍然没有快乐

【问题讨论】:

  • 当它是对象数组时,您试图将其作为字符串数组获取,创建一个 POCO 模型以匹配设置并获取该数组

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


【解决方案1】:

当它是一个对象数组时,你试图将它作为一个字符串数组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[]>();

【讨论】:

    【解决方案2】:

    这可以在java中使用rest-assured库来完成

    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 的工作原理一无所知。但长话短说,这可能会对你有所帮助!!!

    【讨论】:

      猜你喜欢
      • 2017-08-09
      • 1970-01-01
      • 2020-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      • 2013-03-20
      • 2018-09-03
      相关资源
      最近更新 更多