11

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.

Ph0en1x
  • 9,943
  • 8
  • 48
  • 97

3 Answers3

6

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;
    }
}
Sane
  • 2,334
  • 2
  • 17
  • 20
1

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.

adem caglin
  • 22,700
  • 10
  • 58
  • 78
-1

I may not have get the question nor the context right, but if you want to work with raw json or json token, you may should use the Newtonsoft library.

As exemple, admitting that Configuration is an object, you may use JsonConvert.SerializeObject() in order to transform your object in a JSON string (it also work the other way round). You can also work with the JObject library which is provided in the same packet, and which contain LINQ tools.

For exemple, the below code just read your json file wich contain the given serialize object, and load into a .Net object.

String filecontent = "";
StreamReader s = new StreamReader(file.OpenReadStream());
filecontent = s.ReadToEnd();    
contractList = JsonConvert.DeserializeObject<YourObject>(filecontent); 

I really don't know if I get it right, but the question confused me. For exemple, could you precise how you load your json ? Which type is the object where yo ustore it (the Configuration one I gess ?) ? Etc....

Shad
  • 57
  • 1
  • 10