获取ConfigurationSection的初始JSON表示

时间:2016-05-30 12:23:43

标签: c# json asp.net-core asp.net-core-mvc appsettings

我们假设我们在appsettings.json

中有这一部分
{
  "crypto":{
      "A": "some value",
      "B": "foo foo",
      "C": "last part"
   },
   ...
}

"crypto"是某些加密密钥的json序列化。

稍后在代码中,我需要做这样的事情:

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

Configuration.GetSection返回ConfigurationSection个实例。有办法以某种方式获取原始的json数据吗?

我认为ConfigurationSection.Value应该做的伎俩,但由于某种原因,它总是null

3 个答案:

答案 0 :(得分:2)

这是实施的一个例子。

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

答案 1 :(得分:0)

如果您想获得crypto部分的内容,可以使用 Configuration.GetSection("crypto").AsEnumerable()(或者您的示例Configuration.GetSection("crypto").GetChildren()可能有用)。

但结果不是原始的json。你需要转换它。

答案 2 :(得分:-1)

我可能没有问题也没有上下文相关的内容,但是如果您想使用原始的json或json令牌,则应该使用Newtonsoft library

例如,承认Configuration是一个对象,您可以使用JsonConvert.SerializeObject()来将您的对象转换为JSON字符串(反之亦然)。您还可以使用同一包中提供的JObject库,其中包含LINQ工具。

例如,以下代码仅读取包含给定序列化对象的json文件,然后加载到.Net对象中。

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

我真的不知道我是否正确,但是这个问题使我感到困惑。例如,您能否精确说明如何加载json?您要存储该对象的类型是什么(配置一?)?等等....