Using IConfigurationRoot extension method
public static T GetSectionAsObject<T>(this IConfigurationRoot configuration, string key)
{
return configuration.GetSection(key).Get<T>();
}
I am retrieving sections from configuration file as objects. For example I have a section in configuration file:
"RandomClass": {
"Attribute1": "x",
"Attribute2": "y",
"Attribute3": "z"
},
which gets mapped to an object of class RandomClassSettings
public class RandomClassSettings
{
public string Attribute1 { get; set; }
public string Attribute2 { get; set; }
public string Attribute3 { get; set; }
}
This works.
Unfortunately, in the configuration file I have another section with a key "attribue.RandomAttribue" which won't get mapped to object like in the previous example because of the "." in it's name. Any ideas how to make it possible? I can't rename the key in configuration file.
I tried making another class Attribute and having a class like below, but it doesn't work either.
public class NewClassSettings {
public Attribute attribute { get; set; }
}
Edit: I am using .NET Framework 4.7.2
Data from
appsettings.jsondoesn't get JSON deserialized, a custom JsonConfigurationFileParser takes care of the parsing. AnySystem.Text.JsonnorJson.NETattributes are not being considered.Here, you'll need to apply a ConfigurationKeyNameAttribute on the property of the class representing that data.
Suppose your data looks like below with that mentioned
attribue.RandomAttribuekey.Then your class will need to look like this - you can give the property with the
ConfigurationKeyNameAttributeany name of your choice.You get that data with below call.