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


簡單讀取 json 配置文件

背景

  目前發現網上的 .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 文件的屬性哦:

 

 


相關的文章:

  《[.Net Core] 簡單讀取 json 配置文件

  《[.Net Core] 簡單使用 Mvc 內置的 Ioc

  《[.Net Core] 簡單使用 Mvc 內置的 Ioc(續)

  《[.Net Core] 在 Mvc 中簡單使用日志組件

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM