22

For .NET Core 3.1, console application how can I read a complex object from appsetting.json file and cast it into the corresponding object?

All the examples I see online seem to be for previous versions of .NET core and things seems to have changed since then. Below is my sample code. I don't really know how to proceed from here. Thank you for your help.

appsettings.json

{
  "Player": {
    "Name": "Messi",
    "Age": "31",
    "Hobby": "Football"
  }
}

Player.cs

class Player
{
    public string Name { get; set; }
    public string Age { get; set; }
    public string Hobby { get; set; }
}

Program.cs

static void Main(string[] args)
{
    var config = new ConfigurationBuilder()
        .SetBasePath(Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location))
        .AddJsonFile("appsetting.json").Build();
    var playerSection = config.GetSection("Player");
}
Farhad Zamani
  • 5,381
  • 2
  • 16
  • 41
stuck_inside_task
  • 273
  • 1
  • 2
  • 6

1 Answers1

41

In .Net Core 3.1 you need to install these packages:

  • Microsoft.Extensions.Configuration.Json

  • Microsoft.Extensions.Configuration.FileExtensions

then build IConfiguration:

 static void Main(string[] args)
 {
    IConfiguration configuration = new ConfigurationBuilder()
       .AddJsonFile("appsettings.json", true,true)
       .Build();
    var playerSection = configuration.GetSection(nameof(Player));
}

Reference Configuration in ASP.NET Core

Mohammad Dehghan
  • 17,853
  • 3
  • 55
  • 72
Farhad Zamani
  • 5,381
  • 2
  • 16
  • 41
  • 1
    Ah yes, nice. This gave me what I wanted. Thank you! ``` IConfigurationSection playerSection = configuration.GetSection(nameof(Player)); var name = playerSection["Name"]; ``` – stuck_inside_task Apr 02 '20 at 14:57
  • @stuck_inside_task Glad I could help you :) Good luck – Farhad Zamani Apr 02 '20 at 15:04
  • 9
    For info adding Microsoft.Extensions.Configuration.Json via nuget will also add Microsoft.Extensions.Configuration.FileExtensions – d219 Apr 13 '20 at 21:21
  • 7
    Also worth mentioning you should set `Copy to Output Directory=Copy always` for your newly added appsettings.json file. – Iztoksson Jun 29 '21 at 06:25
  • What if I need to read a settings json file from a .NET 3.1 class library assembly (dll), can I use this mechanism, since there is no "Main" entry point in the assembly? – Alberto Silva May 25 '22 at 17:59