我如何访问列表< object>来自AppSettings.json?

发布于 2025-02-06 12:42:13 字数 917 浏览 2 评论 0原文

在我的appsettings.json中,我有一个类似的字段


    "MyFields" : [
    {
    "name":"one",
    "type":"type1"
    "parameters":[{"key":"url","value":"myurl.com"}, {"key":"data","value":"mydata"}]
    },
    {
    "name":"two",
    "type":"type2"
    ...
    ..
    and so on
    }
    ]

我已经制作了一个具有以下属性的Myfield:


    public class MyField
        {
            [JsonProperty]
            public string? name { get; set; }
    
            [JsonProperty]
            public string? type { get; set; }
    
            [JsonProperty]
            public IDictionary<string,string>? parameters { get; set; }
        }

我正在尝试使用配置在其他类中访问它


    //config is the configuration
       var myFields = config.GetSection("MyFields").Get<List<MyField>>();

, 。但是,当我通过消除“参数”字段来做同样的事情时,它就会像魅力一样工作。

我知道这与不当匹配有关,但要获得一些帮助会很棒。

In my appsettings.json I have a field like this


    "MyFields" : [
    {
    "name":"one",
    "type":"type1"
    "parameters":[{"key":"url","value":"myurl.com"}, {"key":"data","value":"mydata"}]
    },
    {
    "name":"two",
    "type":"type2"
    ...
    ..
    and so on
    }
    ]

I have made a class Myfield with the following properties:


    public class MyField
        {
            [JsonProperty]
            public string? name { get; set; }
    
            [JsonProperty]
            public string? type { get; set; }
    
            [JsonProperty]
            public IDictionary<string,string>? parameters { get; set; }
        }

And I am trying to access it in an other class using the config, like this :


    //config is the configuration
       var myFields = config.GetSection("MyFields").Get<List<MyField>>();

the problem is that myFields turn out to be empty. But when I do the same thing by eliminating the "parameters" field then it works like a charm.

I know its something related to improper matching but it'll be great to get some help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

晨曦慕雪 2025-02-13 12:42:14

你有一个错误,应该是

    public Dictionary<string, string>[] parameters { get; set; }

     //or
    public  List<Dictionary<string, string>> parameters { get; set; }

,但也许这会更有效

public  List<KeyValue> parameters { get; set; }
....

public class KeyValue
{
    public string key {get; set;}
    public string value {get; set;}
 }

you have a bug, should be

    public Dictionary<string, string>[] parameters { get; set; }

     //or
    public  List<Dictionary<string, string>> parameters { get; set; }

but maybe this would be more effiecient

public  List<KeyValue> parameters { get; set; }
....

public class KeyValue
{
    public string key {get; set;}
    public string value {get; set;}
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文