How does the configuration binder handle nested objects and arrays when binding a JSON section to a strongly-typed C# class?
Short answer
The binder uses reflection to match configuration keys (flattened into a colon-delimited hierarchy internally) to corresponding property names, recursively binding nested objects, and mapping JSON arrays to numerically-indexed keys (Items:0, Items:1) that bind to List or array…
Advertisement
AModel answer
The binder uses reflection to match configuration keys (flattened into a colon-delimited hierarchy internally) to corresponding property names, 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 matching the configuration structure.
// appsettings.json
{
"Settings": {
"MaxRetries": 3,
"Endpoints": ["https://a.com", "https://b.com"]
}
}
public class Settings {
public int MaxRetries { get; set; }
public List<string> Endpoints { get; set; } = new();
}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