Reputation: 85
I am trying to extract from appsettings.json
"BulkMailCodes": {
"NcoaCorrectedCodes": {
"A": "Full match",
"91": "Matched despite missing secondary number",
"92": "Matched despite extra secondary number"
},
"NcoaSuppressedCodes": {
"0": "No matching address",
"1": "New address is Outside US",
"2": "No forwarding address",
"3": "PO Box closed",
}
How can I get the key/value pairs for "BulkMailCodes":"NcoaCorrectedCodes" into a Dictionary or KeyValuePair object?
I have this class:
class BulkMail
{
public static IConfigurationRoot configuration = GetConfig();
Dictionary<string, string> ncoaCorrected, ncoaSuppressed;
static void Main(string[] args)
{
BulkMail bulkMail = new BulkMail();
}
public BulkMail()
{
ncoaCorrected = configuration["BulkMailCodes: CassSuppressedCodes"];
Console.WriteLine("NcoaCorrectedCodes: ");
foreach (KeyValuePair<string, string> pair in ncoaCorrected)
{
Console.WriteLine(string.Format("{0}: {1}", pair.Key, pair.Value));
}
}
public static IConfigurationRoot GetConfig()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
return (builder.Build());
}
}
Thanks!
Upvotes: 0
Views: 741
Reputation: 4376
All you have to do is bind it to an object of type Dictionary. You will need to add a nugget package: Microsoft.Extensions.Configuration.Binder You can do it like this:
class BulkMail
{
public static IConfigurationRoot configuration = GetConfig();
private Dictionary<string, string> ncoaCorrected = new Dictionary<string, string>();
private Dictionary<string, string> ncoaSuppressed = new Dictionary<string, string>();
static void Main(string[] args)
{
BulkMail bulkMail = new BulkMail();
}
public BulkMail()
{
configuration.GetSection("BulkMailCodes:NcoaCorrectedCodes").Bind(ncoaCorrected);
configuration.GetSection("BulkMailCodes:NcoaSuppressedCodes").Bind(ncoaSuppressed);
Console.WriteLine("NcoaCorrectedCodes: ");
foreach(KeyValuePair<string, string> pair in ncoaCorrected)
{
Console.WriteLine(string.Format("{0}: {1}", pair.Key, pair.Value));
}
Console.WriteLine("NcoaSuppressedCodes: ");
foreach(KeyValuePair<string, string> pair in ncoaSuppressed)
{
Console.WriteLine(string.Format("{0}: {1}", pair.Key, pair.Value));
}
Console.ReadLine();
}
public static IConfigurationRoot GetConfig()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
return (builder.Build());
}
}
Upvotes: 0
Reputation: 1658
ncoaCorrected = configuration.GetSection("BulkMailCodes:NcoaCorrectedCodes").GetChildren()
.ToDictionary(x => x.Key, x => x.Value);
Console.WriteLine("NcoaCorrectedCodes: ");
foreach (KeyValuePair<string, string> pair in ncoaCorrected)
{
Console.WriteLine(string.Format("{0}: {1}", pair.Key, pair.Value));
}
Upvotes: 1