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.
public static class ConfigurationExtensions
{
public static IConfigurationBuilder AddJsonString(this IConfigurationBuilder configurationBuilder, string json)
{
configurationBuilder.Add(new JsonStringConfigurationSource(json));
return configurationBuilder;
}
}
public class JsonStringConfigurationSource : IConfigurationSource
{
private readonly string _json;
public JsonStringConfigurationSource(string json) => _json = json;
public IConfigurationProvider Build(IConfigurationBuilder builder) => new JsonStringConfigurationProvider(_json);
}
public class JsonStringConfigurationProvider : ConfigurationProvider
{
private readonly string _json;
public JsonStringConfigurationProvider(string json) => _json = json;
public override void Load() => Data = JsonConvert.DeserializeObject<Dictionary<string, string>>(_json);
}
Example usage:
{
"key3": "value3",
"key2": "value2",
"key1": "value1"
}
var config = new ConfigurationBuilder().AddEnvironmentVariables().AddJsonString(input).Build();
Console.WriteLine(config["key1"]); // value1
Console.WriteLine(config["key2"]); // value2
Console.WriteLine(config["key3"]); // value3