Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get initial JSON representation of ConfigurationSection

Let's assume we have this section in appsettings.json

{
  "crypto":{
      "A": "some value",
      "B": "foo foo",
      "C": "last part"
   },
   ...
}

Where "crypto" is json serialization of some cryptographic key.

Later in the code, I need to make something like this:

var keyOptions = CryptoProvider.RestoreFromJson(Configuration.GetSection("crypto"))

But Configuration.GetSection return ConfigurationSection instance. Is there a way to get raw json data behind it somehow?

I assumed that ConfigurationSection.Value should do the trick, but for some reason it's always null.

like image 678
Ph0en1x Avatar asked May 30 '16 12:05

Ph0en1x


2 Answers

Here is an example impelementaion.

private static JToken BuildJson(IConfiguration configuration)
{
    if (configuration is IConfigurationSection configurationSection)
    {
        if (configurationSection.Value != null)
        {
            return JValue.CreateString(configurationSection.Value);
        }
    }

    var children = configuration.GetChildren().ToList();
    if (!children.Any())
    {
        return JValue.CreateNull();
    }

    if (children[0].Key == "0")
    {
        var result = new JArray();
        foreach (var child in children)
        {
            result.Add(BuildJson(child));
        }

        return result;
    }
    else
    {
        var result = new JObject();
        foreach (var child in children)
        {
            result.Add(new JProperty(child.Key, BuildJson(child)));
        }

        return result;
    }
}
like image 93
Sane Avatar answered Nov 02 '22 04:11

Sane


If you want to get content of crypto section, you can use Configuration.GetSection("crypto").AsEnumerable()(or for your example Configuration.GetSection("crypto").GetChildren() may be useful).

But the result is not raw json. You need to convert it.

like image 20
adem caglin Avatar answered Nov 02 '22 05:11

adem caglin