Brian
Brian

Reputation: 1989

How can I convert my appsettings.json section to an object?

I have an appsettings.json that looks like this:

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "AllowedHosts": "*",
    "SearchExclusions": {
        "Classifications": {
            "title": "My First Title",
            "entries": [ "ALPHA", "BETA" ]
        },
        "SubjectContains": {
            "title": "My Second Title",
            "entries": [ "GAMMA", "DELTA", "EPSILON", "ZETA", "ETA", "THETA", "IOTA", "KAPPA" ]
        }
    }
}

My .RAZOR component looks like this:

@inject IConfiguration Configuration
<h1> My Component </h1>
@code {
    protected override void OnInitialized()
    {
        // This does not work.
        var searchExclusionsObject = Configuration.GetSection("SearchExclusions").Get<SearchExclusions>();

        // This also does not work.
        var searchExclusionsObject = Configuration.Get<SearchExclusions>();
    }

    private class SearchExclusions
    {
        private Classifications classifications { get; set; }
        private SubjectContains subjectContains { get; set; }
    }

    private class Classifications
    {
        private String title { get; set; }
        private String[] entries { get; set; }
    }

    private class SubjectContains
    {
        private String title { get; set; }
        private String[] entries { get; set; }
    }
}

Upvotes: 0

Views: 1409

Answers (2)

Youness Abbassi
Youness Abbassi

Reputation: 11

Absolutely, it's just the accessibility of your properties that needs to be changed from Private to Public

Upvotes: 0

Jefferson Raposo
Jefferson Raposo

Reputation: 183

All your properties on SearchExclusions and other child classes are private, they need to be public.

Upvotes: 3

Related Questions