Read JSON as string from Microsoft.Extensions.Configuration

1k Views Asked by At

Microsoft.Extensions.Configuration has its own API for navigating through the JSON contained in the config file it reads in. (This is what ASP.NET uses for configuration)

For a given JSON node- is there a way to get access to its contents as a string rather than as more Configuration objects? I have JSON objects in my config file which I need to run through a JSON deserializer (so I just want to read this node from the file as a string).

Something akin to the following:

var myObjectsSection = configuration.GetSection("MyObjects");
var innerText = myObjectsSection.InnerText; //Is there any way to do this???
var myObjs = JsonConvert.DeserializeObject<MyObject[]>(innerText);

Config file:

{
   "SomeSetting": "mySetting",
   "MyObjects": [
        {
            ...
        },
        {
            ...
        }
   ]
}
1

There are 1 best solutions below

0
Sibrin On

Asp.net core 3 has a method for getting type-related configuration value: T IConfigurationSection.Get<T>()

I've tried to parse the custom configuration which you described and it is working.

appsetting.json:

{
  "CustomSection": [
    {
      "SomeProperty": 1,
      "SomeOtherProperty": "value1"
    }
  ]
}

Startup class:

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            this.Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            IConfigurationSection section = this.Configuration.GetSection("CustomSection");
            var configs = section.Get<List<CustomSectionClass>>();
        }

        public class CustomSectionClass
        {
            public int SomeProperty { get; set; }
            
            public string SomeOtherProperty { get; set; }
        }
    }