NET问答: 不能从 appsettings.json 中以 string[] 形式读取?
咨询区
-
Notbad:
我尝试从 appsettings.json 中读取一些对象,json 格式大概如下:
{
"DevicePool": [
{
"device": "185.215.0.91:9082",
"phonePair": [ "644004268", "644049008" ],
"enabled": "true"
},
{
"device": "185.215.0.92:9083",
"phonePair": [ "644491698", "644935005" ],
"enabled": "true"
}
]
}
然后我尝试以下面的代码进行读取。
public DevicePoolMgr(IConfiguration configuration, string devicePoolConfigKey)
{
_devices = new List<DevicePoolItem>();
_configuration = configuration;
string adbPath = Startup.AppConfig["AppConstants:AdbPath"];
var valuesSection = _configuration.GetSection(devicePoolConfigKey);
foreach (IConfigurationSection section in valuesSection.GetChildren())
{
bool enabled = section.GetValue<bool>("enabled");
if (!enabled) continue;
string device = section.GetValue<string>("device");
var phoneNumbers = section.GetValue<string[]>("phonePair");
DevicePhonePair phonePair = new DevicePhonePair(phoneNumbers[0], phoneNumbers[1]);
_devices.Add(new DevicePoolItem() {Device = device, PhonePair = phonePair, Enabled = enabled});
}
}
代码执行后,我可以获取到 device 和 enabled 值,但是我获取 phonePair 节的时候返回 null,我已看过别人就是用这种方式从 appsettings.json 中获取 string数组 的,所以我不知道为什么这里不行?
回答区
-
Raju Melveetilpurayil :
不知下面的代码是否满足你的要求,先创建一个用来序列化的 DevicePool,定义如下:
public class DevicePool
{
public string device { get; set; }
public List<string> phonePair { get; set; } = new List<string>();
public bool enabled { get; set; }
}
然后用下面的方式读取。
var devicePools= _configuration.GetSection("DevicePool").Get<List<DevicePool>>();
点评
从提问者提供的解析代码来看,他还是按照解析 xml 的思路解读 .net core 的 appsetting.json,显而易见后者是以 json 格式组织的,而且 .netcore 为了能够花式解析 appsetting.json, 专门提供了一个帮助类 ConfigurationBinder
,定义如下。
public static class ConfigurationBinder
{
public static void Bind(this IConfiguration configuration, object instance);
public static void Bind(this IConfiguration configuration, object instance, Action<BinderOptions> configureOptions);
public static void Bind(this IConfiguration configuration, string key, object instance);
public static object Get(this IConfiguration configuration, Type type);
public static object Get(this IConfiguration configuration, Type type, Action<BinderOptions> configureOptions);
public static T Get<T>(this IConfiguration configuration);
public static T Get<T>(this IConfiguration configuration, Action<BinderOptions> configureOptions);
public static object GetValue(this IConfiguration configuration, Type type, string key, object defaultValue);
public static T GetValue<T>(this IConfiguration configuration, string key);
public static T GetValue<T>(this IConfiguration configuration, string key, T defaultValue);
}
原文链接:https://stackoverflow.com/questions/64431169/imposible-to-read-array-of-strings-form-appsettings-json-in-asp-dot-net-3-1