欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

.NET Core簡單讀取json配置文件

 更新時(shí)間:2018年03月31日 11:57:24   作者:反骨仔  
這篇文章主要為大家詳細(xì)介紹了.NET Core簡單讀取json配置文件,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

背景

  目前發(fā)現(xiàn)網(wǎng)上的 .NET Core 讀取 json 格式的配置文件有點(diǎn)麻煩,自己想搞個(gè)簡單點(diǎn)的。

  .NET Core 目前的主流形式是采用 json 格式來存儲(chǔ)配置文件信息,跟之前的諸如 app.config 和 web.config 等 xml 形式的配置文件有所區(qū)別。 

json 文件 demo

appsettings.json:

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

Nuget 類庫引用

  需要 Nuget 兩個(gè)類庫:

 ?、費(fèi)icrosoft.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");
   //創(chuàng)建配置根對(duì)象
   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();
  }
 }
}

測(cè)試結(jié)果:

直觀的關(guān)系對(duì)比圖,可以看到核心就是 GetSection() 方法,每繼續(xù)往下一個(gè)層次獲取就再次調(diào)用 GetSection() 方法:

備注

別忘了設(shè)置 json 文件的屬性哦:

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論