BlogUsing a JSON string as a configuration source for a .NET Core project

The following errors were encountered: Please rectify them and try again.

I recently had a project at work that I wanted to pass in a JSON string as a means of configuration. There is a .NET package that will read in a JSON file, but not one to read in a string. So below you will find a set of classes I made to take in a JSON string and parse it in to the application config using the Newtonsoft JSON library.

  1. public static class ConfigurationExtensions
  2. {
  3. public static IConfigurationBuilder AddJsonString(this IConfigurationBuilder configurationBuilder, string json)
  4. {
  5. configurationBuilder.Add(new JsonStringConfigurationSource(json));
  6. return configurationBuilder;
  7. }
  8. }
  9.  
  10. public class JsonStringConfigurationSource : IConfigurationSource
  11. {
  12. private readonly string _json;
  13.  
  14. public JsonStringConfigurationSource(string json) => _json = json;
  15.  
  16. public IConfigurationProvider Build(IConfigurationBuilder builder) => new JsonStringConfigurationProvider(_json);
  17. }
  18.  
  19. public class JsonStringConfigurationProvider : ConfigurationProvider
  20. {
  21. private readonly string _json;
  22.  
  23. public JsonStringConfigurationProvider(string json) => _json = json;
  24.  
  25. public override void Load() => Data = JsonConvert.DeserializeObject<Dictionary<string, string>>(_json);
  26. }

Example usage:

  1. {
  2. "key3": "value3",
  3. "key2": "value2",
  4. "key1": "value1"
  5. }

  1. var config = new ConfigurationBuilder().AddEnvironmentVariables().AddJsonString(input).Build();
  2. Console.WriteLine(config["key1"]); // value1
  3. Console.WriteLine(config["key2"]); // value2
  4. Console.WriteLine(config["key3"]); // value3

Posted on Wednesday the 3rd of October 2018