无法将appsettings IConfiguration节反序列化为类型化元素的数组



我正试图从我的appsettings.json文件中检索一个IConfiguration节,该文件是一个强类型元素数组,但我一直得到一个空集合。在反序列化IConfiguration部分时,我使用默认情况下Asp .Net Core 3.1使用的任何内容:

(我将JsonSerializer用于所有json特定任务(

DTO

public class Element
{
[JsonPropertyName("key")]
public string Key {get;set;}
[JsonPropertyName("value")]
public string Value{get;set;}
}
public class Elements
{
[JsonPropertyName("fields")]
public IEnumerable<Element>Fields{get;set;}
}
public class Config
{
[JsonPropertyName("elements")]
public Elements Elements{get;set;}
}

appsettings.json

{
"config":{
"fields":[
{"key":"a","value":"aa"},
{"key":"b","value":"bb"},
{"key":"c","value":"cc"}
}
}

启动

public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration) {
this.Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services) {
Config config=this.Configuration.GetSection("config").Get<Config>(); // elements count is 0
Elements elements =  this.Configuration.GetSection("config:elements").Get<Elements>();  // elements count is 0

}
}

我试过:

  • 将类型化元素的IEnumerable(Elements(更改为ArrayListIList无效
  • 将我的Elements字段直接放置在根目录中,但无效

p.S
如果我从[SomeCollection]<Element>更改为[SomeCollection]<string>,它会看到所有元素,因此在反序列化类型集合时显然存在问题。

您可以将Elements更改为List<Element>,下面是一个演示:

DTO:

public class Element
{
[JsonPropertyName("key")]
public string Key { get; set; }
[JsonPropertyName("value")]
public string Value { get; set; }
}

public class Config
{
[JsonPropertyName("fields")]
public List<Element> Fields { get; set; }
}

启动:

Config config=this.Configuration.GetSection("config").Get<Config>(); 

更新:

另一种方式:

DTO:

public class Element
{
[JsonPropertyName("key")]
public string Key {get;set;}
[JsonPropertyName("value")]
public string Value{get;set;}
}
public class Elements
{
[JsonPropertyName("fields")]
public IEnumerable<Element>Fields{get;set;}
}
public class Config
{
[JsonPropertyName("elements")]
public Elements Elements{get;set;}
}

启动:

Elements elements = this.Configuration.GetSection("config").Get<Elements>(); 
Config config= new Config { Elements = elements };

最新更新