简体   繁体   English

如何将 JSON 文件读入字符串指定值并使用 System.Text.Json?

[英]How to read JSON file into string specifying values and using System.Text.Json?

I have a.Net Core 3.1 console application (not an ASP.NET Core) with SQL Server connection, where connection string is stored in appsettings.json file我有一个带有 SQL 服务器连接的.Net Core 3.1 控制台应用程序(不是 ASP.NET 核心),其中连接字符串存储在 appsettings.json 文件中

{"ConnectionStrings": { "DefaultConnection":"Server=sqlserver;Database=appDb;User=username;Password=password;" }}

Previously I used Json.Net to read a string以前我使用 Json.Net 读取字符串

var connString = JObject.Parse(File.ReadAllText("appsettings.json")).GetValue("ConnectionStrings").SelectToken("DefaultConnection").ToString()

and it worked fine.它工作得很好。 Now I decided to switch to System.Text.Json library and having issues with dynamic deserialization.现在我决定切换到 System.Text.Json 库并遇到动态反序列化问题。 The following code throws an exception:以下代码引发异常:

var dict = JsonSerializer.Deserialize<Dictionary<string, string[]>>("appsettings.json");

System.Text.Json.JsonException: ''a' is an invalid start of a value. System.Text.Json.JsonException:“a”是值的无效开始。 Path: $ |路径:$ | LineNumber: 0 |行号:0 | BytePositionInLine: 0.' BytePositionInLine:0。 Inner Exception JsonReaderException: 'a' is an invalid start of a value.内部异常 JsonReaderException:“a”是值的无效开始。 LineNumber: 0 |行号:0 | BytePositionInLine: 0.字节位置内线:0。

Then I would read from a dictionary specifying Where Key == "ConnectionStrings", and then subsequent Value of string array == "DefaultConnection".然后我会从字典中读取指定 Where Key ==“ConnectionStrings”,然后是字符串数组的后续值 ==“DefaultConnection”。 I did not reach that point yet, because of an Exception, so I did not planned how to read from a Dictionary yet.由于异常,我还没有达到那个点,所以我还没有计划如何从字典中阅读。

How can I use a new System.Text.Json library to read a connection string from appsettings.json file?如何使用新的 System.Text.Json 库从 appsettings.json 文件中读取连接字符串? Is it correct to deserialize to Dictianory<string, string[]> ?反序列化为Dictianory<string, string[]>是否正确? Or it would be better to use Dictianory<string, Dictianory<string, string>> ?还是使用Dictianory<string, Dictianory<string, string>>会更好?

JsonSerializer.Deserialize expects a JSON string, not the name of a file. JsonSerializer.Deserialize需要一个 JSON 字符串,而不是文件名。

You need to load the file into a string and then pass that to the Deserialize method:您需要将文件加载到字符串中,然后将其传递给Deserialize方法:

var json = File.ReadAllText("appsettings.json");
var dict = JsonSerializer.Deserialize<Dictionary<string, string[]>>(json);

I've used the api in JsonDocument for this purpose:为此,我在 JsonDocument 中使用了 api:

var json = File.ReadAllText("appsettings.json");
var appSettings = JsonDocument.Parse(json, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip });
var result = appSettings.RootElement.GetProperty("ConnectionStrings").GetProperty("DefaultConnection").GetString();  

HTH高温高压

One of the benefits of System.Text.Json is that it can easily and efficiently deserialize directly from a Stream . System.Text.Json的好处之一是它可以轻松有效地直接从Stream反序列化。 When reading JSON from I/O such as a file or HTTP request, it's better to just deserialize the Stream directly and avoid the unnecessary allocations and memory required to read it into a string first. When reading JSON from I/O such as a file or HTTP request, it's better to just deserialize the Stream directly and avoid the unnecessary allocations and memory required to read it into a string first.

using var reader = new StreamReader("appsettings.json");
var dict = await JsonSerializer.DeserializeAsync<<Dictionary<string, string[]>>(reader.BaseStream);

That being said, for the specific case of reading the appsettings.json , it's better to use the configuration tools built-in to the .NET Generic Host instead of manually parsing the JSON.话虽如此,对于读取appsettings.json的具体情况,最好使用 .NET Generic Host 内置的配置工具,而不是手动解析 Z0ECD11C1D7A287401D148A23BBDDA7。 This gives added benefits such as the ability to override these settings using environment variables and/or command line switches, as well as more easily moving them to another storage system such as KeyVault.这带来了额外的好处,例如能够使用环境变量和/或命令行开关覆盖这些设置,以及更轻松地将它们移动到另一个存储系统,如 KeyVault。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM