Build configuration from multiple json files

EuroEager2008 171 Reputation points

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

Filestructure by samples:


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?

Microsoft Technologies based on the .NET software framework.
3,623 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Lucas Amorim 0 Reputation points

    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
    // ..
    // ..
    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



    Have a nice day,

    Lucas Amorim