You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 19:42:18