Java教程

配置系统

本文主要是介绍配置系统,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

读取配置文件

{
  "persons": [
    {
      "id": 100,
      "info": {
        "name": "msy",
        "age": 18,
        "skills": [ "CSharp", "Java", "Python" ]
      }
    },
    {
      "id": 101,
      "info": {
        "name": "wxb",
        "age": 19,
        "skills": [ "Javascript", "sql", "ruby" ]
      }
    },
    {
      "id": 102,
      "info": {
        "name": "zwj",
        "age": 20,
        "skills": [ "Go", "Php", "Rust" ]
      }
    }
  ]
}
IConfigurationBuilder configBuilder = new ConfigurationBuilder();
// optional=true 找不到配置文件抛出异常  reloadOnChange=true 配置文件被修改,内存也跟着变,false,配置文件被修改,内存不变
configBuilder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
IConfigurationRoot configRoot = configBuilder.Build();

/* 读取简单类型,如数字,字符串,GUID,DateTime,这种方式读取的类型都是字符串,需要自己进行类型转换。
 */
// 查询第1个人员的名字和年龄
Console.WriteLine(configRoot["persons:0:info:name"]);
Console.WriteLine(int.Parse(configRoot.GetRequiredSection("persons:0:info")["age"]));
Console.WriteLine(configRoot.GetSection("persons:0:info:name").Value);
Console.WriteLine(configRoot.GetRequiredSection("persons:0:info").GetValue<int>("age"));
// 查询所有的人员掌握的技能
IEnumerable<IConfigurationSection> sections = configRoot.GetSection("persons").GetChildren();
foreach (IConfigurationSection section in sections)
{
    IEnumerable<IConfigurationSection> skills = section.GetSection("info:skills").GetChildren();
    foreach (IConfigurationSection skill in skills)
    {
        Console.WriteLine(skill.Value);
        Console.WriteLine(skill.Path);
        Console.WriteLine(skill.Key);
    }
}

/* 读取复杂类型,映射到类
 */
// 查询第1个人员的名字和年龄
ObjectPersonModel model = configRoot.GetSection("persons:0:info").Get<ObjectPersonModel>(options => options.ErrorOnUnknownConfiguration = true);
Console.WriteLine(model.name);
Console.WriteLine(model.age);
Console.WriteLine(string.Join(",", model.skills));
var ret = configRoot.GetSection("persons").Get<IList<RelationalPersonModel>>();
Console.WriteLine(ret[0].id);

这篇关于配置系统的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!