【发布时间】:2021-10-06 09:11:09
【问题描述】:
在 ASP.NET Core 2.2 中,我尝试将 JSON 对象数组绑定到匹配的 C# 对象,但它没有正确绑定成员。 (剧透:Test1 有效,Test2 无效。)
在我的 appsettings.json 中,我有这个配置:
{
"Test1": [
"A",
"B",
"C"
],
"Test2": [
{ "s": "A" },
{ "s": "B" },
{ "s": "C" }
]
}
这是以一种非常标准的方式被拉入 Program 类中的 Configuration 对象的,这对我来说对于所有其他目的都很好。
public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json",optional: false, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
在我的程序中,我创建了一个与 Test2 数组中的对象匹配的类。
public class Test2Class
{
public string s;
}
最后,我像这样绑定它们:
List<string> test1 = new List<string>();
Program.Configuration.Bind("Test1", test1);
List<TestClass> test2 = new List<TestClass>();
Program.Configuration.Bind("Test2", test2);
当我检查结果时,我得到的是:
test1 = ["A", "B", "C"]
test2 = [{s: null}, {s: null}, {s: null}]
为了正确绑定 Test2 数组,我需要做些什么不同的事情?
【问题讨论】:
-
TestClass.s应该是一个属性而不是一个字段
标签: json asp.net-core-2.2 appsettings c#-7.0