美文网首页dotNET我爱编程.NET
.Net Core 读取Json配置文件

.Net Core 读取Json配置文件

作者: HapplyFox | 来源:发表于2018-11-19 16:24 被阅读8次

初学.Net Core,很多细节还不熟悉,打算一步一步来学,能学多少就看时间有多少,时间就像海绵里的水,挤一挤总还是有的嘛。

.Net Core读取配置文件相较于以往的方式还是有很大的不同,以往的方式大多要引用System.Configuration 这个类库,且内容要写在app.setting配置文件中才可操作,然后使用底层提供的方法.getConfiguration || .getAppsetting来得到我们需要的数据。

.NetCore读取文件就有了很大的不同,其中变化明显的就是,文件使用Json格式保存,可以自定义名称和内部结构,读取也相当方便,使用层级结构的方式一步一步读取。

一般读取配置文件的方式不做演示,可自行百度,主要通过俩种方式对读取方式进行说明

第一种方式

第一步
首先新建一个.netcore 控制台应用


image.png

第二步
安装 Microsoft.AspNetCore 组件

Install-Package Microsoft.AspNetCore

第三步
新建一个.json文件,填写内容并配置属性


image.png

jsconfig1.json内容

{
  "name": "zhb",
  "age": "10"
}

第四步

     static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder();
            builder.AddJsonFile("jsconfig1.json");

            var configuration = builder.Build();

            Console.WriteLine($"name:{configuration["name"]}  age:{configuration["age"]}");

            Console.Read();
        }

通过这种方式,只需要对json文件进行添加,然后就可以通过configuration变量对内容操作,configuration["name"]就代表得到当前json文件key="name" 的值,特别容易理解

第二种方式

与一种方式其他并无太大差别,只是引用了其他的组件库

Nuget 类库引用

需要 Nuget 两个类库:

①Microsoft.Extensions.Configuration

②Microsoft.Extensions.Configuration.Json

json文件配置

appsettings.json

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

方法体

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

测试结果

image.png

对比图

image.png

相关文章

网友评论

    本文标题:.Net Core 读取Json配置文件

    本文链接:https://www.haomeiwen.com/subject/qmlafqtx.html