Search code examples
c#.net-coreconsole-application.net-6.0

How to get values from Json file in console app?


I have a .Net 6 console app.

I have installed (Latest versions)

Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Json

I manually create an appsettings.json file in the root folder.

In my program.cs i add

var configuration = new ConfigurationBuilder()
     .AddJsonFile($"appsettings.json");

var config = configuration.Build();
var customString = config.GetSection("Custom:Customisation");

The JSON file contents are

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "Custom": {
    "Customisation": {
      "FieldOne": "ThisIsValueOne",
      "FieldTwo": "ValueTwo"
    }
  },

  "Something": {
    "SomthingElsoe": {
      "MoreSetting": "1"
    }

  }
}
  1. Its finds the section but i cant see any of the values for FieldOne etc, what change do i need?
  2. Could i convert this to a C# class so i have strongly typed properties with values?

Regarding question 2 i did research on this and i noticed i needed builder.Services but this isnt available in the Console app?


Solution

  • You Can use this code for solve your problem that First Read Data and Convert To class

    You must install packages below

    Microsoft.Extensions.Configuration.FileExtensions 
    Microsoft.Extensions.Configuration
    Microsoft.Extensions.Configuration.Json
    
    var builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", optional: false);
    
    IConfiguration config = builder.Build();
    var myFirstClass = config.GetSection("Custom:Customisation").Get<Customisation>();
    
    

    Class

     public class Customisation
        {
            public string FieldOne { get; set; }
            public string FieldTwo { get; set; }
        }