本文鏈接:https://blog.csdn.net/yenange/article/details/82457761
參考: https://github.com/liuzhenyulive/JsonReader
在 Web 應用程序中, 獲取配置文件還是比較簡單的, 可以參考:
https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.1#json-configuration-provider
但在控制台和類庫中如何處理呢?
為了與 Web 保持一致, 配置文件名稱還是使用:
appsettings.json
{
"ServerCode": "99",
"section0": {
"UserId": "1",
"UserName": "Tome"
},
"section1": {
"UserId": "2",
"UserName": "Marry"
}
}
下面展示了直接取字符串、綁定到實體及取子節點的幾種方式:
using Microsoft.Extensions.Configuration;
using System;
namespace ConsoleApp4
{
class Program
{
//安裝 .net core 2.1 完整包
//install-package Microsoft.AspNetCore.All -version 2.1.0
//注意不要超過 依賴項->SDK->Microsoft.NETCore.App 的版本,我這里是 2.1.0
//否則會無法正常生成和運行
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
Console.WriteLine($"ServerCode:{configuration["ServerCode"]}");
UserInfo user1 = new UserInfo();
UserInfo user2 = new UserInfo();
configuration.GetSection("section0").Bind(user1);
configuration.GetSection("section1").Bind(user2);
Console.WriteLine(user1.ToString());
Console.WriteLine(user2.ToString());
Console.WriteLine($"section0:UserId:{configuration["section0:UserId"]}");
Console.Read();
}
}
public class UserInfo
{
public long UserId { get; set; }
public string UserName { get; set; }
public override string ToString()
{
return string.Format($"UserId:{UserId}, UserName:{UserName}");
}
}
}
還有一個問題: UserName 后面的值, 如果換成中文, 會顯示亂碼, 這個如何解決?
經 lindexi_gd 兄指點, 用 notepad++ 打開 json 文件, 改成 utf-8 編碼, 就可以讀取中文了, 表示感謝!
————————————————
版權聲明:本文為CSDN博主「吉普賽的歌」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/yenange/article/details/82457761