Home > Net >  How can I read part of appsettings.json as raw string in .net core 5?
How can I read part of appsettings.json as raw string in .net core 5?

Time:11-06

I use C# and .net core web api. I have following appsettings.json:

appsettings.json

How can I read the red part (as is, without parsing - raw text) of this appsettings.json?

I know that I can put this in separate file and then read like this:

var googleServiceAccount = File.ReadAllText("GoogleServiceAccount.json");

But I want to put them in appsettings.json. Any ideas?

CodePudding user response:

Your best bet is to change the type of the "ServiceAccount" field to a string, and then take what appears to be uninterpreted JSON and stringify it, escaping appropriately (shown is the \" to escape the embedded quotes).

{
    "Google": {
        "ServiceAccount": "{ \"type\": \"x\", \"project_id\": \"x\" ... }"
    }
}

Also, you can't have multiline strings in JSON,

    "ServiceAccount": "{
       "you": "cant",
       "do": "this"
    }"

so you'd have to insert \\n, which escapes the \ itself leaving a newline \n in the string or try one of the other suggestions in the referenced link.

{
    "Google": {
        "ServiceAccount": "{\\n \"type\": \"x\",\\n \"project_id\": \"x\" ... \\n}"
    }
}

If you really want to somehow designate a portion of the JSON as a string using some sort of magic (e.g. knowing that specific real pieces of JSON should be strings) then you'd have to build your own magic parser (custom configuration provider) that will essentially violate the JSON spec.

I highly recommend you don't do this as it will confuse everyone!

CodePudding user response:

Try this

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;


IConfiguration configuration = new ConfigurationBuilder()
        .AddJsonFile(@"C:\....\appsettings.json")
        .Build();

 List<KeyValuePair<string,string>> items = configuration
        .GetSection("Google:ServiceAccount")
        .Get<Dictionary<string, string>>()
        .ToList();

foreach (var item in items) Console.WriteLine($"({item.Key},{item.Value})");

or you can use dependency injection instead of configuration builder

public class MyClass
{
   public MyClass(IConfiguration configuration)
{
List<KeyValuePair<string,string>> items = configuration
        .GetSection("Google:ServiceAccount")
        .Get<Dictionary<string, string>>()
        .ToList();
.....
}
}
  • Related