How does the configuration binder handle nested objects, arrays, and complex types when binding a JSON section to a C# class?
Short answer
The configuration binder uses reflection to match configuration keys (flattened into a colon-delimited hierarchy internally, e.g., "Parent:Child:Grandchild") to corresponding property names on the target class, recursively binding nested objects, and mapping JSON arrays to…
Advertisement
AModel answer
The configuration binder uses reflection to match configuration keys (flattened into a colon-delimited hierarchy internally, e.g., "Parent:Child:Grandchild") to corresponding property names on the target class, recursively binding nested objects, and mapping JSON arrays to numerically-indexed keys ("Items:0", "Items:1") that bind to List<T> or array properties -- requiring the target class to have public settable properties (or, in newer versions, support for required/init-only properties and primary constructors in some scenarios) matching the configuration structure.
// appsettings.json
{
"Settings": {
"MaxRetries": 3,
"Endpoints": ["https://a.com", "https://b.com"],
"Nested": { "Timeout": 30 }
}
}
public class Settings {
public int MaxRetries { get; set; }
public List<string> Endpoints { get; set; } = new();
public NestedSettings Nested { get; set; } = new();
}
public class NestedSettings { public int Timeout { get; set; } }Real-world example
A team debugging why a configuration array wasn't binding correctly discovers their JSON used an object with string keys instead of a JSON array, since the binder specifically expects sequential numeric indices to map to a List<T> or array property.
Likely follow-ups
- How does binding handle configuration keys that don't match any property?
- Can the binder populate a Dictionary<string, T> from configuration?
Related topics