【问题标题】:Get initial JSON representation of ConfigurationSection获取 ConfigurationSection 的初始 JSON 表示
【发布时间】:2016-09-28 06:43:08
【问题描述】:

假设我们在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

【问题讨论】:

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


    【解决方案1】:

    这是一个例子。

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        我可能没有正确理解问题或上下文,但如果您想使用原始 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 ?您存储它的对象是哪种类型(我猜的配置?)?等等……

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-03-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多