I’m trying to read Letters as Dictionary from the appsettings.json file. My json contains:
"Words": [ "Alpha", "Beta", "Gama" ], "Letters": [ { "A": "Alpha" }, { "B": "Bravo" }, { "C": "Charlie" } ],
I use configuration class:
public class AppSettingsConfiguration { public List<string> Words { get; set; } = default!; public Dictionary<string, string> Letters { get; set; } = default!; }
property Words is corrected read from .json, but Letters throw exception ‘Cannot create instance of type ‘System.String’ because it is missing a public parameterless constructor.’
If I tried
List<(string, string)> Letters { get; set; } or List<KeyValuePair<string, string>> Letters { get; set; }
I get all 3 lines, but all empty – (null, null)
What is correct property for reading dictionary?
Answer
Dictionary is serialized differently in C#. Please see following JSON:
"Letters": { "A": "Alpha", "B": "Bravo", "C": "Charlie" }