Как прочитать массив словаря из настроек - PullRequest
0 голосов
/ 28 апреля 2020

Из настроек приложения. json Я хочу прочитать эти настройки:

  "CountryPhoneSetting": [
    {
      "US": {
        "DialCode": "+1",
        "CanSMS": true,
        "CanVerify": true
      }
    }
  ]

Это класс, в котором я хочу сохранить его:

    public class CountryPhoneSetting
{
    public IDictionary<string, CountryDetails> CountryInfo {
        get;set;
    }

    public class CountryDetails
    {
        public string DialCode { get; set; }

        public bool CanSMS { get; set; }

        public bool CanVerify { get; set; }
    }

}

Я прошел через решения stackoverflow, но ни одно из них не работает.

Пожалуйста, помогите

Ответы [ 3 ]

2 голосов
/ 28 апреля 2020

Я пишу небольшое расширение для своего проекта. Вы можете попробовать это тоже

using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Text;

namespace MyProject.Utilities
{
    public static class ConfigurationHelper
    {
        public static T Load<T> (this IConfiguration configuration, string section) where T : new()
        {
            if (typeof(T).IsValueType)
            {
                return LoadStruct<T>(configuration, section);
            }
            return LoadClass<T>(configuration, section);
        }   

        private static T LoadStruct<T>(IConfiguration configuration, string section)
        {
            return configuration.GetSection(section).Get<T>();
        }

        private static T LoadClass<T>(IConfiguration configuration, string section) where T:  new()
        {
            T variable = new T();
            configuration.GetSection(section).Bind(variable);
            return variable;
        }
    }
}

Использование:

configuration.Load<List<CountryPhoneSetting>>("CountryPhoneSetting")

Редактировать: Reuired пакет - Microsoft.Extensions.Configuration.Binder

Также в зависимости от объекта в использовании appsettings должно быть так:

configuration.Load<List<Dictionary<string, CountryDetails>>>("CountryPhoneSetting")
2 голосов
/ 28 апреля 2020

Попробуйте изменить json на:

"CountryPhoneSetting": {
    "CountryInfo": {
      "US": {
        "DialCode": "+1",
        "CanSMS": true,
        "CanVerify": true
      },
      "BR": {
        "DialCode": "+55",
        "CanSMS": true,
        "CanVerify": true
      }
    }
  }

И ваш класс на:

public class CountryPhoneSetting
{
     public Dictionary<string, CountryDetails> CountryInfo { get; set; } = new Dictionary<string, CountryDetails>();

     public class CountryDetails
     {
        public string DialCode { get; set; }
        public bool CanSMS { get; set; }
        public bool CanVerify { get; set; }
     }
}

Использование:

Configuration.GetSection("CountryPhoneSetting").Bind(CountryPhoneSetting);

Я проверял это, и это сработало для меня!

См .: https://weblog.west-wind.com/posts/2017/dec/12/easy-configuration-binding-in-aspnet-core-revisited

0 голосов
/ 28 апреля 2020

Обратите внимание на Extra [] после CountryPhoneSetting. Это массив словарей.

public class CountryPhoneSetting
{
    [JsonProperty("CountryPhoneSetting")]
    public Dictionary<string, CountryDetails>[]  CountryInfo {get;set;}
}

public class CountryDetails
{
    [JsonProperty("DialCode")]
    public string DialCode { get; set; }
    [JsonProperty("CanSMS")]
    public bool CanSms { get; set; }
    [JsonProperty("CanVerify")]
    public bool CanVerify { get; set; }
}


var result  = JsonConvert.DeserializeObject<CountryPhoneSetting>(input);

обеспечит ожидаемое поведение, даже если объединить Dictionary<string, CountryDetails>[] в Dictionary<string, CountryDetails> будет нелегко без четкого определения того, что делать с вводом дублированного ключа

Демонстрационная версия

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...