(十一)Json文件配置
- 接上一节,新建一个项目:JsonConfigSample
- 依然添加Microsoft.AspNetCore.All
- 在项目下新建一个Class.json配置文件
{ "ClassNo": "1", "ClassDesc": "ASP.NET Core 101", "Students": [ { "name": "liuxh", "age": "30" }, { "name": "linhj", "age": "30" }, { "name": "liuxy", "age": "6" }, { "name": "liuss", "age": "1" } ] }
由于Class.json是在项目下,默认不在bin目录中,所以要设置Class.Json的属性,复制到输出目录:始终复制;生成操作:内容,这样编译的时候才会把Class.json加到bin目录中
- 最后,Program.cs
1 var builder = new ConfigurationBuilder().AddJsonFile("Class.json"); 2 var configuration = builder.Build(); 3 4 Console.WriteLine($"ClassNo:{configuration["ClassNo"]}"); 5 Console.WriteLine($"ClassDesc:{configuration["ClassDesc"]}"); 6 Console.WriteLine("Student:"); 7 8 Console.Write(configuration["Students:0:name"] + ":");//Student是数组,读取的方式是数组名:下标:key 9 Console.WriteLine(configuration["Students:0:age"]); 10 11 12 Console.ReadKey();