Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net core ioptions with a dictionary

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?

like image 239
David Vodička Avatar asked Nov 29 '25 18:11

David Vodička


1 Answers

Dictionary is serialized differently in C#. Please see following JSON:

"Letters": {
  "A": "Alpha",
  "B": "Bravo",
  "C": "Charlie"
}
like image 198
MistGun Avatar answered Dec 03 '25 23:12

MistGun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!