Created
September 4, 2022 08:19
-
-
Save laurencee/0c356ec4b06945828ddbd08c9611838a to your computer and use it in GitHub Desktop.
Serialize .NET IConfiguration to json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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