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
{"ConnectionStrings": { "DefaultConnection":"Server=sqlserver;Database=appDb;User=username;Password=password;" }}
Previously I used Json.Net to read a string
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. 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. Path: $ | LineNumber: 0 | BytePositionInLine: 0.' Inner Exception JsonReaderException: 'a' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0.
Then I would read from a dictionary specifying Where Key == "ConnectionStrings", and then subsequent Value of string array == "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?
Is it correct to deserialize to Dictianory<string, string[]>
? Or it would be better to use Dictianory<string, Dictianory<string, string>>
?