【问题标题】:Read JSON values from appvariables in asp.net core when JSON nodes are different at each level当每个级别的 JSON 节点不同时,从 asp.net core 中的 appvariables 中读取 JSON 值
【发布时间】:2018-10-09 07:10:48
【问题描述】:

下面有我在 appvariables.json 文件中提供的示例 JSON。

{   "**Desc1**":
    {
        "Code": "Cd1",
        "Description": "Desc1"
      }
      "**Desc2**":
      {
       "Code": "Cd2",
        "Description": "Desc2"
      }
}

如果这是一个具有相同节点名称的 JSON(突出显示 Desc1,Desc2),那么创建一个类并阅读它对我来说会更容易。

您能否建议如何处理。

由于这需要动态处理方式,我无法创建类。

我想读取来自 appvariables 的 JSON。有没有办法做到这一点?或者请提出更好的处理方式。

【问题讨论】:

    标签: asp.net json asp.net-core configuration-files


    【解决方案1】:

    如果您只想从appvariables.json 文件中读取变量并将值与以下类绑定:

    public class Desc
    {
        public string Code {get;set;}
        public string Description {get;set;}
    }
    

    只需使用ConfigurationBuilder()

    var config= new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appvariables.json", optional: false, reloadOnChange: true)
        .Build();
    var v1=config.GetSection("Desc1").Get<Desc>();
    var v2=config.GetSection("Desc2").Get<Desc>();
    

    编辑

    要检索多个Desc,可以使用GetChildren()

    var v= config.GetChildren()
        .Select(i=>i.Get<Desc>());
    
    foreach(var i in v){
        Console.WriteLine($"Got a variable : {i.Code}---{i.Description}");
    }
    

    编辑2

    您还可以根据需要添加Where 条件来过滤配置:

    var v= config.GetChildren()
        .Where(i=>i.Key.StartsWith("Type"))
        .Select(i=>i.Get<Desc>());
    

    【讨论】:

    • 我提到的样本有 2 个道具。通常会有超过 15 个。类似的场景也会发生在许多这样的 JSON 上。还有其他方法吗
    • “2 个道具”是什么意思?你是说有多个 "Desc1" , "Desc2" , "Desc3" .. ."Desc15" ?如果是这样,为什么不使用循环来获取值?
    • 是的..我想这样做..但是为了通过循环,我想知道可用的此类独立元素的数量,如果我能将 JSON 读取为像它一样完整。有可能吗?
    • @shakthi 你知道章节名称吗?它们是怎么命名的?
    • 每个 json 的部分名称类似于 "Type1","Type2"
    猜你喜欢
    • 1970-01-01
    • 2015-10-05
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多