ASP.NET Core Get Json Array using IConfiguration

后端 未结 14 1982
失恋的感觉
失恋的感觉 2020-11-30 21:49

In appsettings.json

{
      \"MyArray\": [
          \"str1\",
          \"str2\",
          \"str3\"
      ]
}

In Startup.cs

相关标签:
14条回答
  • 2020-11-30 22:09
    public class MyArray : List<string> { }
    
    services.Configure<ShipmentDetailsDisplayGidRoles>(Configuration.GetSection("MyArray"));
    
    public SomeController(IOptions<MyArray> myArrayOptions)
    {
        myArray = myArrayOptions.Value;
    }
    
    0 讨论(0)
  • 2020-11-30 22:10

    This worked for me; Create some json file:

    {
        "keyGroups": [
            {
                "Name": "group1",
                "keys": [
                    "user3",
                    "user4"
                ]
            },
            {
                "Name": "feature2And3",
                "keys": [
                    "user3",
                    "user4"
                ]
            },
            {
                "Name": "feature5Group",
                "keys": [
                    "user5"
                ]
            }
        ]
    }
    

    Then, define some class that maps:

    public class KeyGroup
    {
        public string name { get; set; }
        public List<String> keys { get; set; }
    }
    

    nuget packages:

    Microsoft.Extentions.Configuration.Binder 3.1.3
    Microsoft.Extentions.Configuration 3.1.3
    Microsoft.Extentions.Configuration.json 3.1.3
    

    Then, load it:

    using Microsoft.Extensions.Configuration;
    using System.Linq;
    using System.Collections.Generic;
    
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    
    configurationBuilder.AddJsonFile("keygroup.json", optional: true, reloadOnChange: true);
    
    IConfigurationRoot config = configurationBuilder.Build();
    
    var sectionKeyGroups = 
    config.GetSection("keyGroups");
    List<KeyGroup> keyGroups = 
    sectionKeyGroups.Get<List<KeyGroup>>();
    
    Dictionary<String, KeyGroup> dict = 
                keyGroups = keyGroups.ToDictionary(kg => kg.name, kg => kg);
    
    0 讨论(0)
  • 2020-11-30 22:11

    Recently I also had a need to read a simple array of strings from an appsettings.json file (and other similar .json configuration files).

    For my approach, I created a simple extension method that does the trick:

    public static class IConfigurationRootExtensions
    {
        public static string[] GetArray(this IConfigurationRoot configuration, string key)
        {
            var collection = new List<string>();
            var children = configuration.GetSection(key)?.GetChildren();
            if (children != null)
            {
                foreach (var child in children) collection.Add(child.Value);
            }
            return collection.ToArray();
        }
    }
    

    The original poster's .json file looked as follows:

    {
          "MyArray": [
              "str1",
              "str2",
              "str3"
          ]
    }
    

    Using the above extension method, it makes reading this array a very simple one-line affair, as seen in the following example:

    var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
    string[] values = configuration.GetArray("MyArray");
    

    At runtime, setting a breakpoint with a 'QuickWatch' on values verifies that we have successfully read the values from the .json configuration file into a string array:

    0 讨论(0)
  • 2020-11-30 22:18

    You can install the following two NuGet packages:

    using Microsoft.Extensions.Configuration; 
    using Microsoft.Extensions.Configuration.Binder;
    

    And then you'll have the possibility to use the following extension method:

    var myArray = _config.GetSection("MyArray").Get<string[]>();
    
    0 讨论(0)
  • 2020-11-30 22:21

    You can get the array direct without increment a new level in the configuration:

    public void ConfigureServices(IServiceCollection services) {
        services.Configure<List<String>>(Configuration.GetSection("MyArray"));
        //...
    }
    
    0 讨论(0)
  • 2020-11-30 22:25

    If you have array of complex JSON objects like this:

    {
      "MySettings": {
        "MyValues": [
          { "Key": "Key1", "Value":  "Value1" },
          { "Key": "Key2", "Value":  "Value2" }
        ]
      }
    }
    

    You can retrieve settings this way:

    var valuesSection = configuration.GetSection("MySettings:MyValues");
    foreach (IConfigurationSection section in valuesSection.GetChildren())
    {
        var key = section.GetValue<string>("Key");
        var value = section.GetValue<string>("Value");
    }
    
    0 讨论(0)
提交回复
热议问题