16

TL;DR: How do I read a complex JSON object from appsettings.json?

I have a .NET Core 2.x application with multiple types of configuration values. appsettings.json looks like the snippet below and I am trying to read the value of ElasticSearch:MyIndex:mappings as a single string or JSON object.

{
"ConnectionStrings": {
    "redis": "localhost"
},
"Logging": {
    "IncludeScopes": false,
    "Debug": {
        "LogLevel": {
            "Default": "Warning"
        }
    },
    "Console": {
        "LogLevel": {
            "Default": "Warning"
        }
    }
},
"ElasticSearch": {
    "hosts": [ "http://localhost:9200" ],
    "MyIndex": {
        "index": "index2",
        "type": "mytype",
        "mappings": {
            "properties": {
                "property1": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "location": {
                    "type": "geo_point"
                },
                "code": {
                    "type": "string",
                    "index": "not_analyzed"
                }
            }
        }
    }
}
}

I am able to read the simple config values (key:value pairs) without issue by calling Configuration.GetValue<string>("ElasticSearch:MyIndex:index").

Configuration.GetSection Configuration.GetSection("ElasticSearch:MyIndex:mappings").Value gives me a null value for Value.

Configuration.GetValue Configuration.GetValue<string>("ElasticSearch:MyIndex:mappings") also returns a null value. This makes sense to me as the section has a null value based on the above attempt.

Configuration.GetValue Configuration.GetValue<JToken>("ElasticSearch:MyIndex:mappings") also returns a null value. This makes sense to me as well for the same reason as above.

5
  • Is this just a typo? You have a double :: in the key...
    – DavidG
    Feb 22, 2018 at 18:09
  • @DavidG yes, that is a type in my example which does not occur in my code. Fixing it now. Feb 22, 2018 at 18:10
  • 1
    Also, you can't call .Value on a complex object, that only works for string values.
    – DavidG
    Feb 22, 2018 at 18:11
  • I was trying anything I could think of to see if it would work or help me figure out some other solution. I have been able to get it working by reading appsettings.json as a JSON file and getting the object I need. Feb 22, 2018 at 18:41
  • I have a work around by parsing appsettings.json directly and reading the property I need. But I still would like to see if there are other options. Feb 22, 2018 at 19:51

7 Answers 7

20
Dictionary<string,object> settings = Configuration
    .GetSection("ElasticSearch")
    .Get<Dictionary<string,object>>();
string json = JsonConvert.SerializeObject(settings);
3
  • 1
    .Get<Dictionary<string,object>>(); closing bracket missing Sep 17, 2020 at 17:00
  • 3
    Although i was hoping for this to work, it throws an exception that i can't work around. Any tips? Maybe its working differently now in .NET Core 3.1. System.ArgumentNullException: Value cannot be null. (Parameter 'type') at System.Reflection.IntrospectionExtensions.GetTypeInfo(Type type)
    – morteng
    Oct 1, 2020 at 12:31
  • I'm not sure, have you double checked that Configuration has a child "ElasticSearch" that has children of its own?
    – chris31389
    Oct 1, 2020 at 13:10
3

Read the configuration:

IConfiguration configuration = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true).Build();

Then you can create a POCO that maps the structure of the JSON file (or part of it). For example, if the class name is ConnectionStringsConfiguration

public class ConnectionStringsConfiguration { public string Redis {get; set;} }

then use:

ConnectionStringsConfiguration appConfig = configuration.GetSection("ConnectionStrings").Get<ConnectionStringsConfiguration>();
2

The solution ended up being much simpler than anything I was initially trying: read appsettings.json as any other JSON formatted file.

JToken jAppSettings = JToken.Parse(
  File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "appsettings.json"))
);

string mapping = jAppSettings["ElasticSearch"]["MyIndex"]["mappings"];
3
  • 2
    what is the JToken? where did you get that from? @babak-naffas Jan 7, 2019 at 20:50
  • 3
    There's a lot wrong with this approach. If your settings are overwritten by a different provider, then you won't get updated values unless you are following chris's answer. Sep 16, 2019 at 8:42
  • @It'satrap both solutions end up taking a snapshot of the config value at a point in time the moment they read the value. I would concede your point it the IConfiguration reference itself was being injected into the dependencies. Sep 16, 2019 at 18:45
2

Convert your JSON object to an escaped string. To do this you'll most likely just have to escape all the double quotes and put it on one line so it looks something like:

"ElasticSearch": "{\"hosts\": [ \"http://localhost:9200\" ],\"MyIndex\": {\"index\"... "

Then you could read it into a string that can be parsed by just using:

Configuration["ElasticSearch"]

This solution isn't for everyone since it's not fun to look at or update the escaped json, but if you only plan on rarely making changes to this configuration setting then it might not be the worst idea.

2

@chris31389's solution is a good one and received a vote from me. However, my situation required a more generic solution.

private static IConfiguration configuration;

public static TConfig ConfigurationJson<TConfig>(this string key)
{
  var keyValue = GetJson();
  return Newtonsoft.Json.JsonConvert.DeserializeObject<TConfig>(keyValue);
  
  string GetJson()
  {
     if (typeof(TConfig).IsArray)
     {
         var dictArray = configuration
             .GetSection(key)
             .Get<Dictionary<string, object>[]>();
                
         return Newtonsoft.Json.JsonConvert.SerializeObject(dictArray);
     }

      var dict = configuration
          .GetSection(key)
          .Get<Dictionary<string, object>[]>();
      return Newtonsoft.Json.JsonConvert.SerializeObject(dict);
   }
}

Notes:

  • Nuget `Microsoft.Extensions.Configuration.Binder` is required
  • As @chris31389 identified above, you have to deserialize to a dictionary and then re-serialize to a string or you get null values. This will not work
    configuration
      .GetSection(key)
      .Get<TConfig>()
    
  • If you are trying to deserialize an array a `Dictionary[]` is required. This is why the other solution does not work some times.
1

Simple Example

Use an extension method:

public static class ConfigurationExtensions
{
    public static T GetOptions<T>(this IConfiguration configuration)
        where T : class, new()
        => configuration.GetSection(typeof(T).Name).Get<T>() ?? new T();
}

Then call it like this:

var loggingOptions = configuration.GetOptions<LoggingOptions>();

Slightly Less Simple Example

Here is a more advanced example that uses nested POCOs and arrays. The following are the configuration POCOs:

public class DynamicDnsUpdaterOptions
{
    public Int32 ClientTimeoutInMinutes { get; set; } = 1;
    public Int32 UpdateIntervalInMinutes { get; set; } = 5;
    public Int32 MonitorStatusInMinutes { get; set; } = 60;
    public Int32 ForceUpdateInDays { get; set; } = 30;
    public Boolean EnablePasswordEncryption { get; set; }
    public IReadOnlyCollection<Domain> Domains { get; set; } = Array.Empty<Domain>();
    public IReadOnlyCollection<Provider> Providers { get; set; } = Array.Empty<Provider>();
    public IReadOnlyCollection<IpChecker> IpCheckers { get; set; } = Array.Empty<IpChecker>();
}

public class Domain
{
    public string DomainName { get; set; } = String.Empty;
    public DnsProviderType ProviderType { get; set; }
    public string HostedZoneId { get; set; } = String.Empty;
    public string AccessID { get; set; } = String.Empty;
    public string SecretKey { get; set; } = String.Empty;
    public Int32 MinimalUpdateIntervalInMinutes { get; set; }
    public string LastIpAddress { get; set; } = String.Empty;
    public DateTime? LastUpdatedDateTime { get; set; }
    public string ChangeStatusID { get; set; } = String.Empty;
    public ICollection<String> HistoricalIPAddress { get; set; } = new List<String>();
    public UpdateReasonType LastUpdatedReason { get; set; }
}

public class Provider
{
    public DnsProviderType ProviderType { get; set; }
    public String ProviderUrl { get; set; } = String.Empty;
    public String ApiKey { get; set; } = String.Empty;
}

public class IpChecker
{
    public IpCheckerType IpCheckerType { get; set; }
    public ClientType ClientType { get; set; }
    public string IpCheckerUrl { get; set; } = String.Empty;
}

public enum DnsProviderType
{
    AMAZON_ROUTE_53
}

public enum IpCheckerType
{
    DYN_DNS,
    JSON_IP,
    CUSTOM
}

public enum UpdateReasonType
{
    FORCED,
    CHANGED
}

public enum ClientType
{
    WEB_HTTP
}

The corresponding config section looks like this:

{
    "DynamicDnsUpdaterOptions": {
        "ClientTimeoutInMinutes": 1,
        "UpdateIntervalInMinutes": 6,
        "MonitorStatusInMinutes": 1,
        "ForceUpdateInDays": 30,
        "EnablePasswordEncryption": false,
        "Domains": [
            {
                "DomainName": "something.example.com",
                "ProviderType": "AMAZON_ROUTE_53",
                "HostedZoneId": "<HostedZoneId>",
                "AccessID": "<AccessID>",
                "SecretKey": "<SecretKey>",
                "MinimalUpdateIntervalInMinutes": "5",
                "LastIpAddress": "192.168.111.222",
                "LastUpdatedDateTime": "2015-02-21T19:29:12.8381639Z",
                "ChangeStatusID": "",
                "HistoricalIPAddress": [],
                "LastUpdatedReason": "CHANGED"
            }
        ],
        "Providers": [
            {
                "ProviderType": "AMAZON_ROUTE_53",
                "ProviderUrl": "https://route53.amazonaws.com"
            }
        ],
        "IpCheckers": [
            {
                "IpCheckerType": "JSON_IP",
                "ClientType": "WEB_HTTP",
                "IpCheckerUrl": "http://www.jsonip.com/"
            },
            {
                "IpCheckerType": "DYN_DNS",
                "ClientType": "WEB_HTTP",
                "IpCheckerUrl": "http://checkip.dyndns.com/"
            },
            {
                "IpCheckerType": "CUSTOM",
                "ClientType": "WEB_HTTP",
                "IpCheckerUrl": "http://ipv4.icanhazip.com/"
            }
        ]
    }
}

And fetch it like this:

var options = configuration.GetOptions<DynamicDnsUpdaterOptions>();

Notes

  • Make sure your POCOs contain sensible default values. If the section does not exist in the appsettings.json, or if it cannot be successfully bound to the POCOs, then the default values of the POCOs will be used.
  • The POCOs must use properties, not fields.
  • Lists or Collections can be difficult to bind. Consider using arrays instead.
0

I get data of configuration by binding it to a class and use as service everywhere, in configureservices i add this class

services.Configure<SiteSettings>(options => Configuration.Bind(options));

then in controller I can access it by dependency injection like below:

private readonly IOptionsSnapshot<SiteSettings> _siteSetting;
public TestController(IOptionsSnapshot<SiteSettings> siteSetting) ......

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.