问题描述
我的环境是 VS Code 和 .NET Core 2.0.
My env is VS Code and .NET Core 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 都为空.字符串数组似乎无效,但它看起来像一个有效的 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 tried a simplified 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 中的字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!