Build configuration from multiple json files

EuroEager2008 141 Reputation points
2023-09-14T20:04:24.9566667+00:00

I have a bunch of json files which all have the same structure.

Filestructure by samples:

{"Item1":{"Prop1"=1}}
{"Item2":{"Prop1"=2}}

I want these read into a .net app configuration as a dictionary (The root of each file is dictionary key, eg "Item1").(The app is using IHost and DI)

Perhaps by something like AddOptions<Dictionary<string, ItemClass>>()

I don't know how to get going, anyone may give me a push in the right direction?

.NET
.NET
Microsoft Technologies based on the .NET software framework.
2,045 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Lucas Amorim 0 Reputation points
    2023-09-18T11:23:59.1233333+00:00

    Hi, @EuroEager2008

    This code might help you!
    Please let me know if there's anything else I can assist you with.

    {
      "MyConfig": {
        "Item1": { "Prop1": 1 },
        "Item2": { "Prop1": 2 }
      }
    }
    
    using System.Collections.Generic;
    using System.IO;
    using Newtonsoft.Json;
    
    public class ItemClass
    {
    	public int Prop1 { get; set; }
    }
    
    public class MyConfig
    {
    	public Dictionary<string, ItemClass> Config { get; set; }
    }
    
    //Startup.cs or Program.cs
    // ..
    services.Configure<MyConfig>(Configuration.GetSection("MyConfig"));
    // ..
    
    public class MyController : Controller
    {
    	private readonly MyConfig _myConfig;
    	public MyController(IOptions<MyConfig> myConfig)
    	{
    		_myConfig = myConfig.Value;
    	}
    
    	public IActionResult Index()
    	{
    		var item1 = _myConfig.Config["Item1"];
    		return View();
    	}
    }
    

    In order for this code to work, you need to provide valid JSON files.
    As @Thomas Wycichowski said: You will need to adjust

    from
    {"Item1":{"Prop1"=1}}

    to
    {"Item1":{"Prop1":1}}

    Have a nice day,

    Lucas Amorim