在程序中经常遇到读取指定Json文件的内容,并把其转换成指定的Model对象,应该如何做呢?
首先要创建需要转换的Model类。
转换方法如下:
public static T GetAppSettings<T>(string fileName, string key) where T : class, new()
{
// 获取bin目录路径
var directory = AppContext.BaseDirectory;
directory = directory.Replace("\", "/");
var filePath = $"{directory}/{fileName}";
if (!File.Exists(filePath))
{
var length = directory.IndexOf("/bin");
filePath = $"{directory.Substring(0, length)}/{fileName}";
}
IConfiguration configuration;
var builder = new ConfigurationBuilder();
builder.AddJsonFile(filePath, false, true);
configuration = builder.Build();
var appconfig = new ServiceCollection()
.AddOptions()
.Configure<T>(configuration.GetSection(key))
.BuildServiceProvider()
.GetService<IOptions<T>>()
.Value;
return appconfig;
}
上面的方法是给定bin目录下指定的json文件名和指定的Key,然后就可以把指定Key下面的Json内容转换成指定的Model对象。