如何从应用程序设置中读取嵌套对象?

问题描述 投票:0回答:1

在我的 .NET Core 应用程序中,我尝试从

appsettings.json
读取数据。

我在

appsettings.json
中有这个配置:

 "ServiceDetails": {
   "CellDetails": {
     "ScenarioName": [ 4, 5 ],
     "ServiceName": [ 5, 5 ]
   }
 }

我想阅读此内容并将其转换为这样的列表:

scenario name, 4,5
service name, 5,5

上述列表的模型类:

 public class CellDetails
 {
     public string CellKeyValue { get; set; }
     public int Row { get; set; }
     public int Column { get; set; }
 }

我正在尝试这样的事情

 var serverUrl = configuration.GetSection("ServiceDetails")
                      .GetSection("CellDetails").Get<string[]>();

上面的代码不起作用,有人可以帮我解决这个问题吗?任何帮助,将不胜感激。谢谢你

c# json asp.net-core appsettings
1个回答
0
投票

你想要这个吗?

var myArray = configuration.GetSection("ServiceDetails:CellDetails:ScenarioName").Get<int[]>();

结果:

更新:

尝试创建一个模型 ServiceDetails,例如:

public class ServiceDetails
{
    public List<CellDetails> CellDetails { get; set; }
}

然后在appsettings.json中:

"ServiceDetails": {
  "CellDetails": [
    {
      "CellKeyValue": "ScenarioName",
      "Row": 4,
      "Column": 5
    },
    {
      "CellKeyValue": "ServiceName",
      "Row": 5,
      "Column": 5
    }
  ]
}

然后

var myArray = configuration.GetSection("ServiceDetails:CellDetails").Get<List<CellDetails>>() ;

结果:

© www.soinside.com 2019 - 2024. All rights reserved.