.NET Core从环境变量反序列化JSON对象数组遇空值求助
解决appsettings.json对象数组反序列化空值问题
方法一:强类型绑定(推荐)
先定义与JSON结构匹配的实体类:
public class AttributeConfig { public string Name { get; set; } public string Type { get; set; } }
直接通过配置系统绑定到列表,无需手动处理JSON:
List<AttributeConfig> adProperties = configuration.GetSection("Attr").Get<List<AttributeConfig>>();
方法二:使用Newtonsoft.Json解析
如果不想定义实体类,需先获取完整的数组JSON字符串,再解析:
// 先获取Attr节点的完整JSON var attrSection = configuration.GetSection("Attr"); var attrJson = attrSection.Get<string>(); // 解析为JArray并遍历 JArray propertiesArray = JArray.Parse(attrJson); List<(string Name, string Type)> adProperties = new List<(string, string)>(); foreach (JObject propertyObject in propertiesArray) { string propertyName = propertyObject["Name"].ToString(); string propertyType = propertyObject["Type"].ToString(); adProperties.Add((propertyName, propertyType)); }
方法三:遍历配置子节点
利用配置系统的子节点遍历功能,直接读取每个对象的属性:
List<(string Name, string Type)> adProperties = new List<(string, string)>(); foreach (var childNode in configuration.GetSection("Attr").GetChildren()) { string name = childNode["Name"]?.Value<string>(); string type = childNode["Type"]?.Value<string>(); if (!string.IsNullOrWhiteSpace(name) && !string.IsNullOrWhiteSpace(type)) { adProperties.Add((name, type)); } }
为什么之前的方法会返回空?
- 直接调用
configuration["Attr"]无法获取数组的完整JSON内容,配置系统对嵌套/数组结构的取值逻辑是扁平化的,必须通过GetSection("Attr")操作节点。 - 用
JArray.Parse(configuration["Attr"])时,传入的参数是null或空字符串,自然解析出空数组。
内容的提问来源于stack exchange,提问作者HaiderMirza
相关产品推荐
相关产品推荐

