Get initial JSON representation of ConfigurationSection Get initial JSON representation of ConfigurationSection json json

Get initial JSON representation of ConfigurationSection


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;    }}


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.


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....