I’m using .NET 6 and I’m trying to declare and bind something like this:
appsettings.json
:
{
"QueryConfigList": [
{
"TableName": "Live",
"QueryText": "SELECT * FROM Live",
"AdditionalInfo": "Users only",
"ObjectClass": {
"TagName": "string",
"Value1": "float"
}
},
{
"TableName": "Orders",
"QueryText": "SELECT * FROM Orders",
"AdditionalInfo": "Completed orders",
"ObjectClass": {
"TagName": "string",
"Value2": "string"
}
}
]
}
In C#:
public class QueryConfig
{
public string? TableName { get; set; }
public string? QueryText { get; set; }
public string? AdditionalInfo { get; set; }
public dynamic? ObjectClass { get; set; }
}
public class QueryConfigList
{
public ICollection<QueryConfig>? QueryConfig { get; set; }
}
I’ve coded something like this in startup.cs
:
var queryConfigList = builder.Configuration.GetSection("QueryConfigList").Get<List<QueryConfig>>();
but I got null
– what is wrong? ChatGpt swears – this should work
Based on the provided data you can use Dictionary<string, string>
for the dynamic part:
public class QueryConfig
{
//...
public Dictionary<string, string>? ObjectClass { get; set; }
}
If that is not suitable for you then I’m afraid you will need to parse the config manually. Something to get you started:
foreach (var entry in builder.Configuration.GetSection("QueryConfigList").GetChildren())
{
foreach (var field in entry.GetChildren())
{
if (field.Key == "ObjectClass")
{
// process dynamic part
}
}
}
Your code works for me, perhaps you’re constructing your configuration incorrectly?
You don’t need the QueryConfigList
class since your config section is a list already.
Code that I tried in a brand new project with your json file:
using Microsoft.Extensions.Configuration;
var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
var queryList = config.GetSection("QueryConfigList").Get<List<QueryConfig>>();
Console.WriteLine($"QueryCt={queryList.Count}");
public class QueryConfig
{
public string? TableName { get; set; }
public string? QueryText { get; set; }
public string? AdditionalInfo { get; set; }
public dynamic? ObjectClass { get; set; }
}