当前位置: 移动技术网 > IT编程>开发语言>.net > .NET Core简单读取json配置文件

.NET Core简单读取json配置文件

2019年05月28日  | 移动技术网IT编程  | 我要评论

西安酒店小姐,永恒之蓝,甜美蛋糕

背景

  目前发现网上的 .net core 读取 json 格式的配置文件有点麻烦,自己想搞个简单点的。

  .net core 目前的主流形式是采用 json 格式来存储配置文件信息,跟之前的诸如 app.config 和 web.config 等 xml 形式的配置文件有所区别。 

json 文件 demo

appsettings.json:

{
 "name": "wen",
 "age": 26,
 "family": {
  "mother": {
   "name": "娘",
   "age": 55
  },
  "father": {
   "name": "爹",
   "age": 56
  }
 }
}

nuget 类库引用

  需要 nuget 两个类库:

  ①microsoft.extensions.configuration

  ②microsoft.extensions.configuration.json

核心代码:

program.cs:

using system;
using system.io;
using microsoft.extensions.configuration;

namespace demo
{
  class program
  {
    static void main(string[] args)
    {
      //添加 json 文件路径
      var builder = new configurationbuilder().setbasepath(directory.getcurrentdirectory()).addjsonfile("appsettings.json");
      //创建配置根对象
      var configurationroot = builder.build();

      //取配置根下的 name 部分
      var namesection = configurationroot.getsection("name");
      //取配置根下的 family 部分
      var familysection = configurationroot.getsection("family");
      //取 family 部分下的 mother 部分下的 name 部分
      var mothernamesection = familysection.getsection("mother").getsection("name");
      //取 family 部分下的 father 部分下的 age 部分
      var fatheragesection = familysection.getsection("father").getsection("age");

      //value 为文本值
      console.writeline($"name: {namesection.value}");
      console.writeline($"mothername: {mothernamesection.value}");
      console.writeline($"fatherage: {fatheragesection.value}");
      console.read();
    }
  }
}


测试结果:

直观的关系对比图,可以看到核心就是 getsection() 方法,每继续往下一个层次获取就再次调用 getsection() 方法:

备注

别忘了设置 json 文件的属性哦:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网