Skip to content

Instantly share code, notes, and snippets.

@laurencee
Created September 4, 2022 08:19
Show Gist options
  • Select an option

  • Save laurencee/0c356ec4b06945828ddbd08c9611838a to your computer and use it in GitHub Desktop.

Select an option

Save laurencee/0c356ec4b06945828ddbd08c9611838a to your computer and use it in GitHub Desktop.
Serialize .NET IConfiguration to json
// Small modification of https://stackoverflow.com/a/62533775/2631967
JToken SerializeConfiguration(IConfiguration config)
{
var obj = new JObject();
foreach (var child in config.GetChildren())
{
if (child.Path.EndsWith(":0"))
{
var arr = new JArray();
foreach (var arrayChild in config.GetChildren())
{
arr.Add(SerializeConfiguration(arrayChild));
}
return arr;
}
obj.Add(child.Key, SerializeConfiguration(child));
}
if (obj.HasValues || config is not IConfigurationSection section) return obj;
// Allow for json that has been embeded as a string in a single key
if (section.Value.StartsWith('{') && section.Value.EndsWith('}'))
{
obj = JObject.Parse(section.Value);
return obj;
}
return ParseJValue(section.Value);
}
private JValue ParseJValue(string value)
{
if (bool.TryParse(value, out var boolean))
return new JValue(boolean);
if (long.TryParse(value, out var integer))
return new JValue(integer);
if (decimal.TryParse(value, out var real))
return new JValue(real);
return new JValue(value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment