我們知道我們可以將 json 檔案決議IConfigurationRoot為
public class Startup
{
public IConfigurationRoot Configuration { get; }
public Startup(IHostingEnvironment env)
{
this.Configuration = new ConfigurationBuilder()
.SetBasePath(path)
.AddJsonFile("somefile.json")
.Build();
}
}
但我想用它ConfigurationBuilder來決議一個 json 字串,這樣就可以像使用 json 檔案一樣訪問它,這樣我就可以做到:
string jsonString = XXX(); // external calls to get json
var config = new ConfigurationBuilder().AddJsonString(jsonString).Build();
string name = config["Student:Name"];
那么imaginal是否AddJsonString存在或者我需要使用任何第三方庫來實作這一點?
附言
我不能使用 JsonSerializer,因為 json 有效負載有太多屬性,因此我無法創建要反序列化的 POJO 模型類,如果只有 3 或 4 個屬性,那么我當然可以這樣做,但是 50 個屬性(即有嵌套屬性)是另一回事
uj5u.com熱心網友回復:
您可以使用new ConfigurationBuilder().AddJsonStream(new MemoryStream(Encoding.ASCII.GetBytes(jsonString))).Build();從 MemoryStream 加載 json。
我的測驗代碼:
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
Configuration = configuration;
string jsonString = "{\"source\": \"test.com\", \"Time\":\"Feb 2019\" }"; // external calls to get json
var config = new ConfigurationBuilder().AddJsonStream(new MemoryStream(Encoding.ASCII.GetBytes(jsonString))).Build();
string name = config["source"];
}
測驗結果(.Net Core 3.1):

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/457067.html
上一篇:Raven.Client.Exceptions.Database.DatabaseDoesNotExistException:'資料庫'*****'不存在
下一篇:如何在表關系C#ASP.NETEntityFrameworkCore6WebAPI中的LINQ方法語法中按表名對列進行分組?
