Martin
Martin

Reputation: 360

Binding Configurations to a Complex Object

In ASP.NET Core 2.2, I'm trying to bind an array of JSON objects to a matching C# object, but it's not binding the members properly. (Spoilers: Test1 works, Test2 doesn't.)

In my appsettings.json, I have this config:

{
    "Test1": [
        "A",
        "B",
        "C"
    ],
    "Test2": [
        { "s": "A" },
        { "s": "B" },
        { "s": "C" }
    ]
}

This is pulled into the Configuration object in the Program class in a pretty standard way that's been working well for me for all other purposes.

public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
   .SetBasePath(Directory.GetCurrentDirectory())
   .AddJsonFile("appsettings.json",optional: false, reloadOnChange: true)
   .AddEnvironmentVariables()
   .Build();

In my program, I created a class that matches the object in the Test2 array.

public class Test2Class
{
    public string s;
}

Finally, I bind them like so:

List<string> test1 = new List<string>();
Program.Configuration.Bind("Test1", test1);
List<TestClass> test2 = new List<TestClass>();
Program.Configuration.Bind("Test2", test2);

When I examine the results, this is what I get:

test1 = ["A", "B", "C"]
test2 = [{s: null}, {s: null}, {s: null}]

What do I need to do differently to bind the Test2 array correctly?

Upvotes: 1

Views: 2785

Answers (1)

Nkosi
Nkosi

Reputation: 247153

TestClass.s should be a property and not a field

public class TestClass {
    public string s { get; set; }
}

The following example can also be used to more conveniently get the desired types

List<string> test1 = Program.Configuration.GetSection("Test1").Get<List<string>>();
List<TestClass> test2 = Program.Configuration.GetSection("Test2").Get<List<TestClass>>();

Reference Bind hierarchical configuration data using the options pattern

Upvotes: 4

Related Questions