David Vodička
David Vodička

Reputation: 33

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?

Upvotes: 3

Views: 2780

Answers (2)

Drag and Drop
Drag and Drop

Reputation: 2734

Saddly The model that match this data is List<Dictionary<string, string>>.
Nothing stop data too look like:

{
    "Words": [
        "Alpha",
        "Beta",
        "Gama"
    ],
    "Letters": [
        { "A": "Alpha" }, 
        { "A": "Alpha", "B": "Bravo" },
        { "B": "Bravo" }
    ]
}

So it's not KeyValuePair<string, string> but a full Dictionary there.

If you want to get back to List<KeyValuePair<string, string>> you can use a simple SelectMany(x=> x)

Live Demo : https://dotnetfiddle.net/CFtWm3

Upvotes: 0

MistGun
MistGun

Reputation: 182

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

"Letters": {
  "A": "Alpha",
  "B": "Bravo",
  "C": "Charlie"
}

Upvotes: 3

Related Questions