目的:从Json文件中读取配置
1)创建一个json文件,设置“如果较新则复制”
{ "Smtp": { "Server": "yx165.com", "Name": "yx", "Password": "123456" }, "Person": { "Name": "Sam", "Age": "20", "Address": { "Post": "010000", "Sheng": "Guangdong" }, "chengji:0": "60", "chengji:1": "70" } }
2)安装Nuget包:Microsoft.Extensions.Configuration,配置系统的基础包
3)安装 Nuget包:Microsoft.Extensions.Configuration.Json,读取Json文件的包
4) ConfigurationBuilder builder = new ConfigurationBuilder();
builder.AddJsonFile("webconfig.json",optional: true,reloadOnChange: true);
optional:文件是否必须 reloadOnChange:是否重加载改变
5) IConfigurationRoot config= builder.Build();
6)读取 config.GetSection("Smtp").value;多级的话: config.GetSection("Smtp:Server").value;config.GetSection("Person:Address:Post").value;
代码如下:
ConfigurationBuilder builder = new ConfigurationBuilder(); builder.AddJsonFile("webconfig.json",optional: true,reloadOnChange: true); IConfigurationRoot config= builder.Build(); var smtp= config.GetSection("Smtp:Server").Value; var person = config.GetSection("Person:chengji:0").Value;
输出:
yx165.com 60
以上方式读取Json文件,只能读取Json中类指定的某个属性,并且如果有多级别,很不方便,所以就想可否直接转换成类,下面我们就来实现
1)安装Nuget包:Microsoft.Extensions.Configuration.Binder,用于对象绑定,也就是把Json转换成类
2)创建绑定对象类,类的属性名称要跟Json文件的名称对应,不区分大小写,注意Json中集合的转换
//对应Json文件的根节点
public class WebConfig { public Person Person { get; set; } public Smtp Smtp { get; set; } } //对应Json文件子节点"Smtp" public class Smtp { public string Server { get; set; } public string name { get; set; } public string password { get; set; } } //对应Json文件子节点"Person" public class Person { public string Name { get; set; } public int Age { get; set; } public Address Address { get; set; } //对应Peson节点中的"chengji:0":"60"和"chengji :1":"70"
public List<int> chengji { get; set; }
}
public class Address
{
public string Post { get; set; }
public string Sheng { get; set; }
}
3)转换绑定和读取,注意根节点的读取可以直接用Get<WebConfig>()
ConfigurationBuilder builder = new ConfigurationBuilder(); builder.AddJsonFile("webconfig.json",optional: true,reloadOnChange: true); IConfigurationRoot config= builder.Build(); //直接读取片段的方式 //var smtp= config.GetSection("Smtp:Server").Value; //var person = config.GetSection("Person:chengji:0").Value; //转换绑定 config.GetSection("Smtp").Bind(new Smtp()); config.GetSection("Person").Bind(new Person()); //读取转换后的对象 Smtp smtp1= config.GetSection("Smtp").Get<Smtp>(); Person person1=config.GetSection("Person").Get<Person>(); //读取根节点 var webConfig= config.Get<WebConfig>();
通过使用转换,就可以直接获取Json转换成对象,方便很多,推荐使用
标签:01,get,C#,Smtp,Person,Json,config,public From: https://www.cnblogs.com/yxh33/p/17899216.html